Vita Rara: A Life Uncommon

Ruby Mastery: The Most Important Chapter You Can Read on Ruby


Categories: | |

There are a decent number of books out there on Ruby. In my mind I consider Chapter 11 of The Ruby Way, 2nd Edition the most important chapter you can read. Here's why.

Mastery in Ruby involves moving past regular programming and embracing the dynamic features of the language. The dynamic nature of Ruby goes far beyond dynamic typing. Frequently programmers coming to Ruby from languages like Java, C++/C#, PHP, VB.Net, and other statically and dynamically typed languages think that dynamic typing is the extent of what is dynamic about Ruby[1]. Chapter 11 of The Ruby Way will greatly disabuse them of this notion and put them on the pathway to Ruby mastery.

So, what is dynamic in Ruby beyond typing? In short metaprogramming, which provides the ability to use code to write code, eliminate repetition and arrive at higher abstractions. Until you start using the metaprogramming facilities of Ruby you're really just writing Java/C++/C# or whatever language you came from in Ruby.

What makes chapter 11 of The Ruby Way so good is it covers most of the advanced facilities of Ruby in a succinct form. The juicy stuff starts in section 11.2 More Advanced Techniques. This sections covers:

  • Sending and Explicit Message to an Object
  • Specializing an Individual Object
  • Storing Code as Objects
  • How Module Inclusion Works
  • Delegating or Forwarding
  • ...and more.

These advanced techniques form the foundation on which to begin your metaprogramming in Ruby. Section 11.3 really starts to dig in, covering:

  • Evaluating Code Dynamically
  • Using const_get
  • Dynamically Instantiating a Class by Name
  • Getting and Setting Instance Variables
  • Using define_method
  • Using const_missing
  • Removing Definitions
  • Obtaining Lists of Defined Entities
  • Handling Calls to Nonexistent Methods
  • Tracking Changes to a Class or Object Definition
  • ... and much more.

If you are coming to Ruby from another language that does not feature metaprogramming as a feature do yourself a favor and pick up a copy of The Ruby Way and read and re-read chapter 11 until you get it.

[1] If you're coming from another dynamic language like Smalltalk or Lisp you already understand what dynamic means.