Could anyone teach me "for in" in Ruby? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

18th Dec 2018, 9:21 AM
Yuta Shimizu
Yuta Shimizu - avatar
4 Answers
+ 1
Thank u so much:)
21st Dec 2018, 11:36 AM
Yuta Shimizu
Yuta Shimizu - avatar
+ 1
In the second code you can write puts i if (i % 5 ==0) All on the same line
21st Dec 2018, 7:14 PM
Nifriz
Nifriz - avatar
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
18th Dec 2018, 9:45 AM
Gordon
Gordon - avatar
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
18th Dec 2018, 9:45 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar