Ruby: Creating destructive methods.

Here's a basic example of using Ruby to create a class with destructive methods. Though this is not as practical as just typing the actual mathematic operations themselves. It does illustrate how destructive functions work and how to write them. Note the 'return self' in each of the destructive methods. This allows you to perform the method chains, without it the method returns a fixnum by default and the method chaining raises an error. If anyone knows of a DRY way to perform this let me know.

class Calculator

  def initialize(value)
    @value = value
  end

  def multiply!(value)
    @value *= value
    return self
  end

  def add!(value)
    @value += value
    return self
  end

  def clear!
    @value = 0
    return self
  end

  def calculate
    puts @value
  end

end

c = Calculator.new(10)
c.add!(2).multiply!(4).calculate #=> 48
c.clear!.add!(5).multiply!(4).calculate #=> 20