Reputation: 1254
Do operators in Ruby belong to a particular class ? As per my knowledge operators are tokens which are redefined by classes according to the operation they are intended to perform. For example the Numeric class defines the + operator for numeric operations, similarly the String class defines it for string concatenation. So based on that if i try to do this:
+.is_a ? (Numeric)
It returns false. Is my explanation to this question correct ?
Sorry for all the confusion this is the actual question from my assignment.What class does + belong to and how do you check it ?
Upvotes: 0
Views: 151
Reputation: 9002
Most of what is an operator in other programming languages, is just a method in Ruby.
+
is a method not an operator. You can get reference to it:
1.method(:+)
#=> #<Method: Fixnum#+>
"".method(:+)
#=> #<Method: String#+>
Fixnum
and String
are ones of many classes that implement +
method. You can define your own operator-like methods:
class MyClass
attr_accessor :number, :string
def +(other)
self.number += other.number
self.string += other.string
self
end
end
Examples of true operators in Ruby, you can't define your own methods with some of these 'names':
=
+=
, -=
, *=
, /=
, %=
, **=
&
, |
, ^
, ~
, <<
, >>
and
, or
, &&
, ||
, !
, not
? :
..
, ...
.
, ::
There is also a special operator defined?
. It actually looks like a method but it's an operator. You can define your own defined?
method, though.
Upvotes: 2
Reputation: 369498
It is pretty confusing what you mean by "belong to class". From your code snippet, it looks like you mean "instance of class".
If that is what you mean, then the answer is: the question doesn't make sense. Operators aren't objects. Therefore they cannot possibly be instances of classes.
Upvotes: 1
Reputation: 23576
No. It dont belong to particural class because any class can has it own +
method. That what you try to do was simply checking the +
operator for the program class. To see that in Ruby everything is a class just run this script
#!/usr/bin/ruby
puts self.inspect
Upvotes: 1