+ 1
Could anyone teach me "for in" in Ruby?
I wanted to get the result of (5 10 15.......100). I got expected result from (1) below. But I couldn't from (2). I want to know why (2) is wrong??? (1) for i in 0..100 next unless i % 5 == 0 puts i end (2) for i in 0..100 puts i next unless i % 5 == 0 end
4 Answers
+ 1
Thank u so much:)
+ 1
In the second code you can write
puts i if (i % 5 ==0)
All on the same line
0
The reason is not about for in.
Instead it is the position of next
Next will jump the following lines and enter the next iteration.
If you put it below puts i
Then puts i will be executed for every iteration, so will output all numbers instead of only multiples of 5
0
#(1)
for i in 0..100
# increase the counter by 1
# if the remainder of the i/5 is 0 then print the counter
next unless i % 5 == 0
puts i
end
puts '================'
#(2)
for i in 0..100
# increase the counter by 1
puts i #print the counter
#if the remainder of the i/5 is 0 then do nothing
next unless i % 5 == 0
end