Ruby 中运算符 ==~ 的含义是什么? [英] What is the meaning of operator ==~ in Ruby?

查看:118
本文介绍了Ruby 中运算符 ==~ 的含义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改现有的 ruby​​ 代码.它有以下几行代码.谁能告诉我这是怎么回事.

I am modifying an existing ruby code. It has the following lines of code. Can somebody tell me what is going on.

if string ==~ /^ABC/
     do-something
elsif string == "some string"
     do-something
else
     do-something
end

这里的if条件是做什么的.我在 google 上搜索 ==~ 运算符,但一无所获.我刚刚找到对 =~ 的解释,这意味着用正则表达式匹配字符串.因此,如果上述 if 条件有单个 = ,则表示检查字符串是否以 ABC 开头.但是当我运行代码时不会发生这种情况.即使字符串以 ABC 开头,它也不会进入 if.

What is the if condition doing here. I googled for ==~ operator and found nothing. I just found explanation for =~, which means matching strings with regular expressions. So, if the above if condition has single = , it means check if string starts with ABC. But that is not happening when i run the code. Even though string starts with ABC, it doesn't go into if.

我不确定这是错误还是故意使用==~

I am not sure if it is a mistake or intentional usage of ==~

推荐答案

一元 ~ 运算符的优先级高于 ===~> 所以这个:

The unary ~ operator has higher precedence than == or =~ so this:

string ==~ /^ABC/

只是一种令人困惑的写作方式:

is just a confusing way of writing:

string == (~/^ABC/)

但是Regexp#~ 做什么?精美的手册说:

But what does Regexp#~ do? The fine manual says:

~ rxp → 整数或零
匹配——将 rxp 与 $_ 的内容进行匹配.相当于rxp =~ $_.

~ rxp → integer or nil
Match—Matches rxp against the contents of $_. Equivalent to rxp =~ $_.

$_ 是字符串的最后输入行由 get 或 readline."这给了我们:

and $_ is "The last input line of string by gets or readline." That gives us:

string == (/^ABC/ =~ $_)

这根本没有任何意义,因为右侧将是一个数字或 nil 而左侧可能是一个字符串.条件只有在 string.nil? 和正则表达式匹配失败时才会为真,但有更好的方法来做到这一点.

and that doesn't make any sense at all because the right hand side will be a number or nil and the left hand side is, presumably, a string. The condition will only be true if string.nil? and the regex match fails but there are better ways to doing that.

我认为您有两个问题:

  1. ==~ 是一个错字,应该是 =~.
  2. 您的测试套件存在漏洞,可能是整个代码库都适合的一个漏洞.
  1. ==~ is a typo that should probably be =~.
  2. Your test suite has holes, possibly one hole that the entire code base fits in.


另请参阅ruby 中的 !=~ 比较运算符是什么?问题.

这篇关于Ruby 中运算符 ==~ 的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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