Quick Ruby Quiz
I was talking to the Dallas Ruby group a couple of days ago, and showed them the following code:
class Fred
class << self
def self.say_hello
puts "Hi!"
end
end
end
Someone asked whether it was possible to call the say_hello method. It is. How many ways can you find?




I can just think of two so far ...
one:
class << Fred
self.say_hello
end
two:
class Object
def singleton_class
class << self; self; end
end
end
Fred.singleton_class.say_hello
ps. Nice idea with the Erlang book!
Posted by: Mariano Kamp | March 08, 2007 at 09:50 AM
(class << Fred ; self ; end).say_hello
Posted by: Tim | March 08, 2007 at 09:51 AM
Oh, and I missed at least one pretty obvious ones.
Fred.new.class.singleton_class.say_hello
Posted by: Mariano Kamp | March 08, 2007 at 09:52 AM
Fred.class_eval{class << self; self end}.say_hello
Posted by: Drew Raines | March 08, 2007 at 10:45 AM
Here is another variation:
class Fred
class << self
self.say_hello
end
end
Posted by: Mark Howe | March 08, 2007 at 02:26 PM
Wow, the readability of that almost reminds me of Perl. Just because something can be done does not mean it should.
Posted by: Dave Dunkin | March 12, 2007 at 11:53 AM
My mistake for the prev entry. Sorry!
Posted by: Herryanto Siatono | March 12, 2007 at 08:45 PM
My other attempt:
class Fred
class << self
def inner_class
class << self; self; end
end
end
end
Fred.inner_class.say_hello
Posted by: Herryanto Siatono | March 12, 2007 at 08:57 PM
You know, this is one of the terrible things about Ruby. Building applications is hard; it doesn't help to have puzzles in your language, as well.
Posted by: Curt Sampson | April 01, 2007 at 12:39 AM
Curt: I disagree. Any decent, interesting language is going to allow you to express your applications cleanly and elegantly. But, at the same time, it will have a depth to it which gives it power. This is an example of that depth. It isn't a puzzle as much as a way of learning about metaclasses. Understand this, and you'll understand a whole bunch of the Ruby MOP.
Dave
Posted by: Dave Thomas | April 13, 2007 at 03:42 PM