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 ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.