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​ Paragraph
 def​ initialize(text)
  @text = text
 end
 
 def​ title?; @text.upcase == @text; ​end
 def​ reverse; @text.reverse; ​end
 def​ upcase; @text.upcase; ​ ...

Get Metaprogramming Ruby 2 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.