Looping differences in Ruby using Range vs. Times
Posted
by jbjuly
on Stack Overflow
See other posts from Stack Overflow
or by jbjuly
Published on 2010-05-28T03:29:15Z
Indexed on
2010/05/28
3:31 UTC
Read the original article
Hit count: 215
I'm trying to solve a Project Euler problem using Ruby, I used 4 different looping methods, the for-loop, times, range and upto method, however the for-loop and times method only produces the expected answer, while the range and upto method does not. I'm assuming that they are somewhat the same, but I found out it's not. Can someone please explain the differences between these methods?
Here's the looping structure I used
# for-loop method
for n in 0..1
puts n
end
0
1
=> 0..1
# times method
2.times do |n|
puts n
end
0
1
=> 2
# range method
(0..1).each do |n|
puts n
end
0
1
=> 0..1
# upto method
0.upto(1) do |n|
puts n
end
0
1
=> 0
© Stack Overflow or respective owner