ruby - Why does a Flip-Flop operator include the second condition? -


the following code using flip-flop operator.

(1..10).each {|x| print "#{x}," if x==3..x==5 } 

why results 3,4,5?

i think should 3,4.

as mentioned in tutorial, expression becomes true when x == 3, , continues true until x == 5. how '5' been printed if evaluates false? please clarify me?

the important link, "the ruby programming language" :

4.6.9.1 boolean flip-flops

when .. , ... operators used in conditional, such if statement, or in loop, such while loop (see chapter 5 more conditionals , loops), not create range objects. instead, create special kind of boolean expression called flip-flop. flip-flop expression evaluates true or false, comparison , equality expressions do. extraordinarily unusual thing flip-flop expression, however, value depends on value of previous evalu- ations. means flip-flop expression has state associated it; must remember information previous evaluations. because has state, expect flip-flop object of sort. isn’t—it’s ruby expression, , ruby interpreter stores state (just single boolean value) requires in internal parsed representation of expression.

with background in mind, consider flip-flop in following code. note first .. in code creates range object. second 1 creates flip-flop expression:

 (1..10).each {|x| print x if x==3..x==5 } 

the flip-flop consists of 2 boolean expressions joined .. operator, in context of conditional or loop. flip-flop expression false unless , until lefthand expression evaluates true. once expression has become true, ex- pression “flips” persistent true state. remains in state, , subsequent evaluations return true until righthand expression evaluates true. when happens, flip-flop “flops” persistent false state. subsequent evaluations of expression return false until lefthand expression becomes true again. in code example, flip-flop evaluated repeatedly, values of x 1 10. starts off in false state, , evaluates false when x 1 , 2. when x==3, flip-flop flips true , returns true. continues return true when x 4 , 5. when x==5, however, flip-flop flops false, , returns false remaining values of x. result code prints 345.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -