为什么 Ruby 不是 Symbol#=~(正则表达式匹配运算符)? [英] Why does Ruby not Symbol#=~ (regex match operator)?

查看:42
本文介绍了为什么 Ruby 不是 Symbol#=~(正则表达式匹配运算符)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 在对符号执行正则表达式匹配时不会自动对符号进行字符串化,当您有包含符号的变量并且忘记在尝试正则表达式匹配之前需要对它们调用 #to_s 时,这很容易做到:

Ruby doesn't automatically stringify symbols when performing a regex match on them, which is easy to do when you have variables containing symbols and you forget that you need to call #to_s on them before trying a regex match:

>> :this =~ /./
=> false
>> :this =~ :this
=> false
>> :this =~ /:this/
=> false

事实证明:=~是在Object中定义的,Ruby 1.8的原始类:

It turns out that :=~ is defined in Object, Ruby 1.8's primordial class:

http://rubybrain.com/api/ruby-1.8.7/doc/index.html?a=M000308&name==~

当然,实现只是返回 false,让 String 和 Regexp 等子类来提供有意义的实现.

Of course, the implementation just returns false, leaving it up to subclasses like String and Regexp to provide meaningful implementations.

那么为什么 Symbol 不提供类似下面的内容呢?

So why doesn't Symbol provide something like the following?

def =~(pattern)
  self.to_s =~ pattern
end

任何 Ruby 语言学家都知道吗?

Any Ruby linguists out there know?

推荐答案

我不知道决定 1.8 应该这样做的原因,但 1.9 在这方面发生了变化:

I don't know the reason why it was decided that 1.8 should behave this way, but 1.9 changed in that regard:

>> RUBY_VERSION #=> "1.9.2"
>> :this =~ /./ #=> 0
>> :this =~ /is/ #=> 2

这篇关于为什么 Ruby 不是 Symbol#=~(正则表达式匹配运算符)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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