Reputation: 31
select = []
0.upto 5 do |value|
select << value if (value==2)...(value==2)
end
p select # [2,3,4,5]
Can anyone tell me how to understand this code?
Upvotes: 3
Views: 65
Reputation: 1492
I learned something researching this because I've never seen the range operator used on boolean values. Apparently in this context its called a "flip flop" operator. Basically, the condition evaluates False
until the first part of the conditional is True
. Then it "flips" and evaluates True
until the 2nd part evaluates True
. In your example, the 2nd part will never evaluate to True
as its already passed the valid condition of value == 2
therefore it will continue on with the range provided. You can see this flip-flopping in action if you change the 2nd condition to value == 4
:
select = []
0.upto 5 do |value|
select << value if (value==2)...(value==4)
end
p select # [2,3,4]
Reference: http://nithinbekal.com/posts/ruby-flip-flop/
Upvotes: 5