Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby define Object#=~?

Tags:

ruby

After reading a comment to an answer in another question and doing a little research, I see that =~ is defined on Object and then overridden by String and Regexp. The implementations for String and Regexp appear to assume the other class:

"123" =~ "123" # => TypeError: type mismatch: String given
/123/ =~ /123/ # => TypeError: can't convert Regexp to String

Although =~ is defined for Object, + is not:

Object.new =~ 1 # => nil
Object.new + 1 # => undefined method `+' for #<Object:0x556d38>

Why has Object#=~ been defined, rather than restricting =~ to to String and Regexp?

like image 358
Eric Walker Avatar asked Dec 22 '12 13:12

Eric Walker


People also ask

Why is everything an object in Ruby?

Ruby is a pure object-oriented language, which means that in the Ruby language, everything is an object. These objects, regardless of whether they are strings, numbers, classes, modules, etc., operate in a system called The Object Model. Ruby offers a method called the object_id , which is available to all objects.

Why is Ruby a object-oriented language?

Ruby is a pure object-oriented language and everything appears to Ruby as an object. Every value in Ruby is an object, even the most primitive things: strings, numbers and even true and false. Even a class itself is an object that is an instance of the Class class.

How do you define an object in Ruby?

You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods. Here, cust1 and cust2 are the names of two objects.

How Ruby uses the object structure?

In `ruby`, the body of an object is expressed by a struct and always handled via a pointer. A different struct type is used for each class, but the pointer type will always be `VALUE` (figure 1). In practice, when using a `VALUE`, we cast it to the pointer to each object struct.


1 Answers

Because it allows any object to be used in a match expression:

Object.new =~ /abc/
=> nil

I guess this makes sense in the way that Object.new does not match the regexp /abc/ and the code would blow up if the left argument wasn't a String object. So it generally simplifies the code because you can have any object on the left side of the =~ operator.

like image 200
Nicholas Avatar answered Oct 05 '22 23:10

Nicholas