-3

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.

3 Answers3

1

The three dots indicates that the end stops before the terminator, two dots indicates it includes the terminator.

SRC: http://strugglingwithruby.blogspot.pt/2008/11/loops.html

1...5 -> 1 to 4

1..5 -> 1 to 5

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • In addition, there's a big difference between using two dots and three dots with Ruby's [flip-flop operator](https://blog.newrelic.com/2015/02/24/weird-ruby-part-3-fun-flip-flop-phenom/). :-) – Cary Swoveland May 01 '16 at 07:04
1

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
]
Alfie
  • 2,706
  • 1
  • 14
  • 28
0

The difference is between inclusive and no inclusive ranges.

i.e.:

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

For this reason, your loops will have a different number of cycles.

Myst
  • 18,516
  • 2
  • 45
  • 67