From: 13 Date: 2006-04-29T00:16:48+09:00 Subject: Re: class returns value without method or attribute Hi, Here is my approach (similar, but longer): $ cat money.rb class Money attr_accessor :value def initialize(value) @value = value end def to_s @value.to_s end def +(other) case other when Money: Money.new(@value + other.value) when Numeric: Money.new(@value + other) else raise "Money can be added to Money or Numeric" end end end irb(main):002:0> money = Money.new 5 => # irb(main):004:0> puts money 5 irb(main):005:0> puts money + money 10 irb(main):006:0> puts money + 100 105 irb(main):007:0> puts money + 'money' RuntimeError: Money can be added to Money or Numeric from ./money.rb:19:in `+' from (irb):7 -- Martins On 4/28/06, Farrel Lifson wrote: > You could overload the methods you require. For instance if you want > to be able to add two Money objects togeter and get a Money object as > the result using the expression 'money1 + money2' you could do > > >> class Money > >> attr_accessor :value > >> def+(other) > >> Money.new(@value + other.value) > >> end > >> def initialize(value) > >> @value = value > >> end > >> end > => nil > >> m1 = Money.new(5) > => # > >> m2 = Money.new(10) > => # > >> m1 + m2 > => # > > Farrel > >