O'Reilly logo

Sams Teach Yourself Ruby in 21 Days by Mark Slagell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Overriding Methods

Ruby is very open-minded about letting you add components to your classes and modules, and even individual objects, after they've already been initially defined:

class Thing
  def talk
    puts "hi"
  end
end

t = Thing.new
t.talk     #output: hi

# Re-open Thing and add a new method.
class Thing
  def shout
    puts "HI!!!"
  end
end

t.shout     #output: HI!!!
# Add a singleton method to object t.
def t.whisper
  puts "(hi)"
end

t.whisper   #output: (hi)

This is just the tip of the iceberg when it comes to the kinds of runtime power Ruby offers you in the area of class and object modification. (And not just your own classes, either. Ruby doesn't put much of the core language behind locked doors.) Here, we're going to put the spotlight on a particular ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required