Interesting excerpts from Programming Ruby
I read these while riding in the car back from Colmar. They’re courtesy of Programming Ruby: The Pragmatic Programmer’s Guide, which I now consider to be one of the most complete and interesting references on Ruby.
Because if itself is an expression, you can get really obscure with statements such as
if artist == "John Coltrane"
artist = "’Trane"
end unless use_nicknames == "no"This path leads to the gates of madness.
def once(*ids) # :nodoc:
for id in ids
module_eval < <-"end;"
alias_method :__#{id.to_i}__, :#{id.to_s}
private :__#{id.to_i}__
def #{id.to_s}(*args, &block)
(@__#{id.to_i}__ ||= [__#{id.to_i}__(*args, &block)])[0]
end
end;
end
endThis code uses module_eval to execute a block of code in the context of the calling module (or, in this case, the calling class). The original method is renamed __nnn__, where the nnn part is the integer representation of the method name’s symbol ID. The code uses the same name for the caching instance variable. A method with the original name is then defined. If the caching instance variable has a value, that value is returned; otherwise the original method is called, and its return value cached and returned.
Understand this code, and you’ll be well on the way to true Ruby mastery.
