Reputation: 1783
This code works as it should be:
puts "pick 1:"
num_1 = gets.chomp
array.detect { |k| k.id == num_1.to_i }
...
puts "pick n:"
num_n = gets.chomp
array.detect { |k| k.id == num_n.to_i }
I am not going to reuse 'num' variable anywhere else so I wanted not to assign gets
to variable and use it in the block, like this:
puts "Pick 1:"
array.detect { |k| k.id == gets.chomp.to_i }
In console sometimes it works sometimes it doesn't. If it doesn't I am stuck in the function.
Is it illegal use or should I somehow wrap gets
?
Upvotes: 1
Views: 140
Reputation: 176372
The two scripts have two different meanings/results.
In the first one you read a number from the input, you store it, then you compare all the items in array against that value.
In the second script, instead, as the "read from input" code is inside the block, it will be executed as part of the detect
iterations. Therefore, you will be asked to input one value (the same value?) as many times as the number of items in the array.
According to what you are asking, the first one is probably the correct approach.
Upvotes: 2