为什么触发器运算符包含第二个条件? [英] Why does a Flip-Flop operator include the second condition?

查看:51
本文介绍了为什么触发器运算符包含第二个条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用了触发器运算符.

The following code is using a flip-flop operator.

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

为什么结果是3,4,5?

我认为应该是3,4.

如教程中所述,当x == 3 时,此表达式为真,并持续为真,直到 x == 5.如果计算结果为 false,如何打印5"?谁能帮我澄清一下?

As mentioned in a tutorial, this expression becomes true when x == 3, and continues to be true until x == 5. How could '5' been printed if it evaluates to false? Could anyone please clarify that for me?

推荐答案

.. 或触发器是从 Perl 继承的,Perl 从 AWK 得到它并在 *nix 中 sed.它非常强大,但在您的特定用途中它相当晦涩,对于您想要的逻辑来说不是一个好的选择,尤其是在 Ruby 中.而是使用:

.. or flip-flop is inherited from Perl which got it from AWK and sed in *nix. It's very powerful, but in your particular use it's fairly obscure and not a good choice for the logic you want, especially in Ruby. Instead use:

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

输出:

3
4
5

也就是说,当您需要从文件中提取一系列行时,它非常强大:

That said, it's extremely powerful when you need to extract a range of lines from a file:

File.foreach('/usr/share/dict/propernames') { |li| puts li if ($. == 5 .. $. == 7) }

输出:

Agatha
Ahmed
Ahmet

Perl 允许仅使用当前读取行的行号(AKA $.) 但 Ruby 不支持.

Perl allows an even more-terse expression using only the line numbers of the currently read line (AKA $.) but Ruby doesn't support that.

还可以选择使用正则表达式,其行为与之前的比较类似:

There's also the option of using regular expressions, which behave similarly as the previous comparison:

File.foreach('/usr/share/dict/propernames') { |li| puts li if (li[/^Wa/] .. li[/^We/]) }

输出:

Wade
Walt
Walter
Warren
Wayne
Wendell

因为正则表达式有效,所以可以创建一个复杂的模式来基于匹配从文件中检索行.作为第一个,然后是第二个模式触发,线被捕获.如果在文件的后面,另一行触发了第一个模式,则将再次进行捕获,直到第二个模式匹配为止.它非常强大:

Because regex work, it's possible to create a complex pattern to retrieve lines from a file based on matches. As the first, then the second pattern trigger, lines are captured. If, later in the file, another line triggers the first pattern, capturing will again occur until the second pattern matches. It's wonderfully powerful:

File.foreach('/usr/share/dict/propernames') { |li| puts li if (
    li[/^Am/] .. li[/^An/] or
    li[/^Wa/] .. li[/^We/]
  )
}

输出:

Amanda
Amarth
Amedeo
Ami
Amigo
Amir
Amos
Amy
Anatole
Wade
Walt
Walter
Warren
Wayne
Wendell

或者,对于我们说晦涩代码的朋友:

Or alternately, for our obscure-code speaking friends:

File.foreach('/usr/share/dict/propernames') { |li| puts li if (li[/^(?:Am|Wa)/] .. li[/^(?:An|We)/]) }

这篇关于为什么触发器运算符包含第二个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆