0

Let's say I have a array:

newArray = Array.[] 

And then I push some strings in it:

newArray.push 'nil'  
newArray.push 'nil2'  
newArray.push 'nil3' 

Now I make a while loop:

while true  
    load = gets.chomp

    if newArray[].include? load  
        puts 'That pieace of the Array is loaded' 
        break 
    end  
end

The part if newArray[].include? load is wrong, I know. But how can I make it so this will work?

4
  • 1
    So you want to check if load is in the array OR if load is a substring of one of the elements in the array? Commented Sep 12, 2014 at 14:51
  • Pretty confident when he says part of array is loaded he actually means that element exists. Commented Sep 12, 2014 at 14:55
  • Yes, what Nobita says! Commented Sep 12, 2014 at 14:56
  • @LuiggiMendoza I want to check if load is a substring of one of the elements in the array, by only typing 0/1/2 (one of those options) Commented Sep 12, 2014 at 15:18

1 Answer 1

3

Your question is confusing, and your code isn't idiomatic Ruby. Consider writing it like:

new_array = []
new_array << 'nil'
new_array << 'nil2'
new_array << 'nil3'

loop do
  load = gets.chomp

  if new_array.include? load
    puts 'That piece of the Array is loaded'
    break
  end
end
  • We use snake_case_for_variables becauseItIsALotEasierToRead.
  • While we can write Array.new or Array.[], we seldom do. We usually assign [] to a variable instead.
  • We typically push to an array using <<. It's shorter to type, and visually sets apart what's happening.
  • Use loop do instead of while true.

I'd actually be more straightforward when defining that array:

new_array = %w[nil nil2 nil3]

And I'd use more mnemonic variable names so the code is more self-documenting:

ary = %w[nil nil2 nil3]

loop do
  user_input = gets.chomp

  if ary.include? user_input
    puts 'That piece of the Array is loaded'
    break
  end
end

If you want to see if the value entered is part of a string element in the array:

if ary.any? { |s| s[user_input] }
  puts 'That piece of the Array is loaded'
  break
end

If you want to see if the value entered is the last character of a string element in the array:

if ary.any? { |s| s[-1] == user_input }

or:

if ary.any? { |s| s[/#{ user_input }$/] }

Read the documentation for any? to understand what it's doing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.