Crazy Singleton Methods
Published 2008-10-17 @ 14:45
So, just about everyone knows about singleton methods… it means you can attach a method to a single individual object. Most often this is used for class methods:
class Person def self.people # return all people end end
Which is fine, but you can also do things to any old instance:
a = "string!" def a.inspect ":symbol!" end p a # => :symbol!
What I didn’t know and learned while working on ruby_parser is that there is another kind of singleton. The above singleton is a variable-based singleton. It requires a variable as the target for the singleton definition.
For example, you can’t do this:
a = Object.new class Object ; def b; end end def a.b.x ; 42; end SyntaxError: compile error (irb):8: syntax error, unexpected '.', expecting '\n' or ';' def a.b.x ; 42; end ^ (irb):8: syntax error, unexpected kEND, expecting $end
BUT! Looking at the grammar, you can do singletons w/ any expression by using parenthesis! Here is an expression-based singleton:
def (a.b).x ; 42; end a.b.x # => 42
Now, the above example is crap… but maybe you’d want to do something like:
class Agent @@tasks =  def self.spawn t = Task.new @@tasks << t t end end def (Agent.spawn).task puts "YAY!" end
No… I still can’t see why you’d want to… but you can.