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
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
=> #<Money:0x2ba41c8 @value=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
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)
=> #<Money:0x2dbb018 @value=5>
>> m2 = Money.new(10)
=> #<Money:0x2db9098 @value=10>
>> m1 + m2
=> #<Money:0x2db17d8 @value=15>
I like the idea of using inspect, will this also allow me to assign
value like:
money = Money.new
money = 5
No, inspect will only affect output with p (or in IRB).
Also do I need to add a method for + and -, is there not a module like
Comparable that I can mixin to get this functionality?
Comparation and arithmetic are two orthogonal concepts, i.e.
completely unrelated. If you want arithmetic in your class, you need
to override +, - and coerce.