James Gray
1/6/2006 5:03:00 PM
On Jan 6, 2006, at 10:35 AM, Bojan Mihelac wrote:
> Hi all,
> I am new to Ruby and am trying to overload "+" operator on Integer
> class, without success.
>
> class TestNum < Integer
> def +(other)
> self.value - other
> end
> end
>
> puts TestNum.new(5)+5; # should return 0
>
> I know that it should be simple, but.... any help appreciated.
Ruby provides the coerce method, for hooking into its math routines:
>> class TestNum
>> def initialize( value )
>> @value = value
>> end
>> attr_reader :value
>> def +( other )
>> if other.is_a? self.class
>> value + other.value
>> else
?> value + other
>> end
>> end
>> def coerce( other )
>> [self.class.new(other), self]
>> end
>> end
=> nil
>> tn = TestNum.new(5)
=> #<TestNum:0x31d2b8 @value=5>
>> tn + 5
=> 10
>> tn + tn
=> 10
>> 5 + tn
=> 10
Hope that helps.
James Edward Gray II