Difference between a 3-point range operator and a 2-point operator in a ruby ​​flip flop

Please help me understand the difference between range operators ...and ..how the “triggers” used in Ruby.

This is an example Pragmatic Programmers manual for 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]
+4
source share
3 answers

The difference between 2 points and 3 points in Ruby is inclusion. for instance

(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.

+3
source

electronics. , . -- , . :

1.upto(10).each do |i|
  puts i if (i%2==0)..(i%4==0)
end

        #                        vvvv   value of "hidden" state
2       # left range boundary  ⇨ true
3
4       # right range boundary ⇨ false, no 5 follows 
6       # left range boundary  ⇨ true
7
8       # right range boundary ⇨ false, no 9 follows 
10

"" true 4- false 3-. 12 , (i%3), .

, .

+3

When a double dot is used in a range, it creates a range of numbers that go up and include the maximum number traversed. When a triple point is used, a range is created that increases, but DOES NOT include the maximum number passed.

So:

 (1..5).each {| i | puts i} #will print 1,2,3,4,5

While:

(1...5).each {| i | puts i} #will print 1,2,3,4
+2
source

Source: https://habr.com/ru/post/1548740/


All Articles