gmuraleekrishna gmuraleekrishna - 1 month ago 8
Ruby Question

Difference between 3-dot-range operator and 2-dot-range operator in flip flop ruby

Please help me to understand the difference between range operators

...
and
..
as "flip-flops" used in Ruby.

This is an example from Pragmatic Programmers guide to Ruby:

a = (11..20).collect {|i| (i%4 == 0)..(i%3 == 0) ? i : nil}


which returns:

[nil, 12, nil, nil, nil, 16, 17, 18, nil, 20]


Also:

a = (11..20).collect {|i| (i%4 == 0)...(i%3 == 0) ? i : nil}


returned:

[nil, 12, 13, 14, 15, 16, 17, 18, nil, 20]

Answer

The difference between 2 dots and 3 dots in Ruby is inclusion. For example

(1..100)
=> All numbers starting from 1 and ending at 100 INCLUDING 100

(1...100)
=> All numbers starting from 1 that are less than 100

(1..100).include?(100)
=> true

(1...100).include?(100)
=> false

Hope this helps.

Comments