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
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With