On Wednesday 09 July 2008, Amitraj singh Chouhan wrote:
there is any please give me the references.
Thanks
amitraj
I’m not sure I undestand correctly what you mean, but I think you have a
wrong
idea of how operators work in ruby. Most operators are simply shortcuts
for
method calls, so that, for example
1 + 3
is translated by the ruby interpreter to
1.+(3)
This means that, when ruby sees the expression 1 + 3, it tries to call
the +
method on the 1 object passing as argument the 3 object. If you write
something like:
1 + ‘a’
ruby will try to pass ‘a’ as argument to the + method of 1. But since
that
method can only handle objects of class Numeric or objects which have a
coerce
method, and strings don’t have it, it raises an exception.
If you want to define operators for your own classes, you simply need to
define the corresponding method:
class C
attr_reader :x
def initialize x
@x = x
end
def +(other)
case other
when Integer then return C.new other + @x
when C then C.new @x + other.x
else raise ArgumentError,“You can’t add an object of class
#{other.class}”
end
end
end
c = C.new 3
c1 = c + 2
puts c1.x
c2 = c + C.new(5)
puts c2.x
c + ‘a’
The above code gives:
5
8
ArgumentError,"You can’t add an object of class String
(note that doing 1+c would raise a TypeError exception, since in this
case the
method call would be 1.+©, instead of c.+(1), and that Integer#+
doesn’t
know how to handle instances of class C).
I hope this helps
Stefano