From: ChrisKaelin Date: 2007-04-21T04:10:09+09:00 Subject: once modifier (pickaxe book page 391) The following code is from the pickaxe book page 391 (slightly modified in order to have it available in all classes, that are defined). It implements a once modifier, that ensures a method's body is only called, if it's return value (an instance variable) is not already set. # Extending Module with the amazing once modifier class Module def once(*ids) # :nodoc: for id in ids module_eval <<-"EOF" alias_method :__#{id.to_i}__, :#{id.to_s} private_methods :__#{id.to_i}__ def #{id.to_s}(*args, &block) (@__#{id.to_i}__ ||= [__#{id.to_i}__(*args, &block)])[0] end EOF end end end It really works very well and is a wonderful example of ruby's power. But I got some noob questions now: - Why isn't this cool method available in ruby directly? - Why can't I use "ids.each" instead of "for id in ids"? Ok, this question has nothing to do with the code itself ;-) - I know what "||=" does (evaluate assignment only, if the left part is false), but what do you call this? Sorry for my lack of these basics and thanks in advance for any answers. Chris