Книга: Metaprogramming Ruby 2
Назад: Class Definitions Demystified
Дальше: Singleton Methods

Quiz: Class Taboo

Where you write an entire program without ever using a certain popular keyword.

Did you ever play Taboo? The rules are simple: you’re given a secret word and a list of words that you cannot use. (They are “taboo.”) You must help a teammate guess the secret word. You can give your teammate as many suggestions as you want, but you must never say a taboo word. If you do that, you lose immediately.

Your challenge: play Taboo with Ruby code. You have only one taboo word, the class keyword. Your “secret word” is actually a Ruby class:

 
class​ MyClass < Array
 
def​ my_method
 
'Hello!'
 
end
 
end

You have to write a piece of code that has exactly the same effect as the previous one, without ever using the class keyword. Are you up to the challenge? (Just one hint: look at the documentation for Class.new.)

Quiz Solution

Because a class is just an instance of Class, you can create it by calling Class.new. Class.new also accepts an argument (the superclass of the new class) and a block that is evaluated in the context of the newborn class:

 
c = Class.new(Array) ​do
 
def​ my_method
 
'Hello!'
 
end
 
end

Now you have a variable that references a class, but the class is still anonymous. Do you remember the discussion about class names in ? The name of a class is just a constant, so you can assign it yourself:

 
MyClass = c

Interestingly, Ruby is cheating a little here. When you assign an anonymous class to a constant, Ruby understands that you’re trying to give a name to the class, and it does something special: it turns around to the class and says, “Here’s your new name.” Now the constant references the Class, and the Class also references the constant. If it weren’t for this trick, a class wouldn’t be able to know its own name, and you couldn’t write this:

 
c.name ​# => "MyClass"

You turn to Bill to show him your solution to the quiz—but he’s already busy browsing the Bookworm source. It’s time to get back to the task at hand.

Назад: Class Definitions Demystified
Дальше: Singleton Methods