Follow me on Twitter!

Dont Trust This Guy why not take my word for it? A blog by Jim Jeffers

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

Leave a Reply

Meta Information

This post was filed under code and tagged with: , .

This Post as a Feed

The content of this post and it's comments can be subscribed to as an RSS feed.

DontTrustThisGuy.com and all contents copyright 2003-2007 by Jim Jeffers, unless otherwise noted.Written in valid XHTML and a participant of XFN while being powered by WordPress
Contents under Creative Commons License. Visual design, layout and Cascading Style Sheets may not be reused without permission.
Entries (RSS) and Comments (RSS)