Ignacio Bricchi Ignacio Bricchi - 7 months ago 11
Ruby Question

Difference between .. and ... in Ruby

What is the difference between .. and ... in a ruby for loop.

for num in 1..5
puts num
end


vs

for num in 1...5
puts num
end


How are those two loops different.

Answer

In ruby 1...5 gives you a range which doesn't include 5 whereas 1..5 gives you a range which does include 5

eg:

>> (1..5).to_a
[
    [0] 1,
    [1] 2,
    [2] 3,
    [3] 4,
    [4] 5
]
>> (1...5).to_a
[
    [0] 1,
    [1] 2,
    [2] 3,
    [3] 4
]