加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 为什么Flip-Flop操作符包含第二个条件?

发布时间:2020-12-16 23:13:12 所属栏目:百科 来源:网络整理
导读:以下代码使用触发器操作符. (1..10).each {|x| print "#{x}," if x==3..x==5 } 为什么结果3,4,5? 我认为它应该是3,4. 如教程中所述,当x == 3时,此表达式变为true,并且在x == 5之前一直为真.如果计算结果为false,那么“5”怎么打印?有人可以请我澄清一下吗
以下代码使用触发器操作符.
(1..10).each {|x| print "#{x}," if x==3..x==5 }

为什么结果3,4,5?

我认为它应该是3,4.

如教程中所述,当x == 3时,此表达式变为true,并且在x == 5之前一直为真.如果计算结果为false,那么“5”怎么打印?有人可以请我澄清一下吗?

解决方法

“Ruby编程语言”的重要环节是:

4.6.9.1 Boolean flip-flops

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读