O'Reilly logo

Metaprogramming Ruby 2 by Paolo Perrotta

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

Singleton Methods

Where it’s your turn to teach Bill a few tricks.

It’s late morning, and you and Bill are deep in the flow. You’re zipping through the Bookworm source, deleting a useless line here, changing a confusing name there, and generally polishing the code…until you bump into a particularly troublesome bit of refactoring.

The Paragraph class wraps a string and then delegates all calls to the wrapped string—all of them, that is, except for one method, Paragraph#title?, which returns true if a Paragraph is all uppercase.

class_definitions/paragraph.rb
 
class​ Paragraph
 
def​ initialize(text)
 
@text = text
 
end
 
 
def​ title?; @text.upcase == @text; ​end
 
def​ reverse; @text.reverse; ​end
 
def​ upcase; @text.upcase; ​ ...

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