« Advanced Ruby Studio | Main | SYWTWAB 3: The Hero's Journey: Are You Experienced? »

March 08, 2007

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?

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d83451c41c69e200d834eabaca53ef

Listed below are links to weblogs that reference Quick Ruby Quiz:

Comments

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!

(class << Fred ; self ; end).say_hello

Oh, and I missed at least one pretty obvious ones.

Fred.new.class.singleton_class.say_hello

Fred.class_eval{class << self; self end}.say_hello

Here is another variation:

class Fred
class << self
self.say_hello
end
end

Wow, the readability of that almost reminds me of Perl. Just because something can be done does not mean it should.

My mistake for the prev entry. Sorry!

My other attempt:

class Fred
class << self
def inner_class
class << self; self; end
end
end
end

Fred.inner_class.say_hello

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.

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

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Now in Beta

  • Programming Ruby, 3rd Edition
    Third Edition, Covering Ruby 1.9, now available
My Photo

Pragmatic Stuff

Photos

  • www.flickr.com
    This is a Flickr badge showing public photos from pragdave tagged with pragdave_badge. Make your own badge here.

Site Search

  • Google Search

    The web
    PragDave