Stefano Crocco
7/9/2008 7:20:00 AM
On Wednesday 09 July 2008, Amitraj singh Chouhan wrote:
> Hi all,
> Ruby is a dynamically typed language so it checks at run time the type
> of the variable and calls corresponding operator. For example "x + y"
> will be checked for type of x and y if both will be fixnum then
> corresponding addition action will be performed if both are strings the
> corresponding appending action will be performed.
> My question is"
> Is there any type specific operator facility available in ruby? If
> somehow we can infer the type of the variables then we can directly use
> those specific operators. I am not aware about any such operator. IF
> 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.+(c), instead of c.+(1), and that Integer#+ doesn't
know how to handle instances of class C).
I hope this helps
Stefano