gberger
gberger

Reputation: 2863

Ruby class inheritance and arithmetic methods

I have this class in Ruby:

class Dollar < BigDecimal
  def initialize(val = 0)
    super val, 2
  end
end

However, the class reverts back to BigDecimal when I do an arithmetic operation.

irb(main):032:0> d = Dollar.new('5')
=> #<BigDecimal:7f12d787bf40,'0.5E1',9(18)>
irb(main):033:0> d.class
=> Dollar
irb(main):034:0> d += Dollar.new('9.99')
=> #<BigDecimal:7f12d786de18,'0.1499E2',18(36)>
irb(main):035:0> d.class
=> BigDecimal

How can I keep it being a Dollar after an arithmetic operation?

Upvotes: 1

Views: 136

Answers (1)

sawa
sawa

Reputation: 168091

You have to redefine the arithmetic operations as well.

class Dollar < BigDecimal
  def + other; Dollar.new(super(other)) end
end

Upvotes: 4

Related Questions