Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby not Symbol#=~ (regex match operator)?

Tags:

ruby

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

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==~

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

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

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

Any Ruby linguists out there know?

like image 656
Josh Glover Avatar asked Feb 03 '11 09:02

Josh Glover


People also ask

What is the symbol of Ruby?

Many cultures have long considered ruby a stone of kings. Not surprisingly, ruby symbolism and lore have many associations with power and wealth. Possessing a ruby purportedly benefited and protected the owner's estates and assisted in the accumulation of wealth.

Why do we use symbols in Ruby?

A simple rule of thumb is to use symbols every time you need internal identifiers. For Ruby < 2.2 only use symbols when they aren't generated dynamically, to avoid memory leaks.

How do you use the NOT operator in Ruby?

The “not” keyword gets an expression and inverts its boolean value – so given a true condition it will return false. It works like “!” operator in Ruby, the only difference between “and” keyword and “!” operator is “!” has the highest precedence of all operators, and “not” one of the lowest. Example 1: Ruby.

How do I create a symbol in Ruby?

Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.


1 Answers

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
like image 62
Michael Kohl Avatar answered Oct 04 '22 21:10

Michael Kohl