(1..10).each {|x| print "#{x}," if x==3..x==5 }
为什么结果3,4,5?
我认为它应该是3,4.
如教程中所述,当x == 3时,此表达式变为true,并且在x == 5之前一直为真.如果计算结果为false,那么“5”怎么打印?有人可以请我澄清一下吗?
解决方法
When the .. and … operators are used in a conditional,such as an if statement,or
in a loop,such as a while loop (see Chapter 5 for more about conditionals and loops),
they do not create Range objects. Instead,they create a special kind of Boolean
expression called a flip-flop. A flip-flop expression evaluates to true or false,just as
comparison and equality expressions do. The extraordinarily unusual thing about a
flip-flop expression,however,is that its value depends on the value of prevIoUs evalu-
ations. This means that a flip-flop expression has state associated with it; it must
remember information about prevIoUs evaluations. Because it has state,you would
expect a flip-flop to be an object of some sort. But it isn’t—it’s a Ruby expression,and
the Ruby interpreter stores the state (just a single Boolean value) it requires in its internal parsed representation of the expression.With that background in mind,consider the flip-flop in the following code. Note that
the first .. in the code creates a Range object. The second one creates the flip-flop
expression:
(1..10).each {|x| print x if x==3..x==5 }
The flip-flop consists of two Boolean expressions joined with the .. operator,in the context of a conditional or loop. A flip-flop expression is false unless and until the lefthand expression evaluates to true. Once that expression has become true,the ex- pression “flips” into a persistent true state. It remains in that state,and subsequent evaluations return true until the righthand expression evaluates to true. When that happens,the flip-flop “flops” back to a persistent false state. Subsequent evaluations of the expression return false until the lefthand expression becomes true again. In the code example,the flip-flop is evaluated repeatedly,for values of x from 1 to 10. It starts off in the false state,and evaluates to false when x is 1 and 2. When x==3,the flip-flop flips to true and returns true. It continues to return true when x is 4 and 5. When x==5,the flip-flop flops back to false,and returns false for the remaining values of x. The result is that this code prints 345.