meta_eval
The equivalent of class_eval for singleton classes. Evaluates the given block in
the context of the receiver??™s singleton class.
meta_def
Defines a method within the receiver??™s singleton class. If the receiver is a class or
module, this will create a class method (instance method of the receiver??™s singleton
class).
class_def
Defines an instance method in the receiver (which must be a class or module).
Metaid??™s convenience lies in its brevity. By using a shorthand for referring to and
augmenting metaclasses, your code will become clearer rather than being littered
with constructs like class << self; self; end. The shorter and more readable these
techniques are, the more likely you are to use them appropriately in your programs.
This example shows how we can use Metaid to examine and simplify our singleton
class hacking:
class Person
def name; "Bob"; end
def self.species; "Homo sapiens"; end
end
Class methods are added as instance methods of the singleton class:
Person.instance_methods(false) # => ["name"]
Person.metaclass.instance_methods -
Object.metaclass.instance_methods # => ["species"]
Using the methods from Metaid, we could have written the method definitions as:
Person.class_def(:name) { "Bob" }
Person.meta_def(:species) { "Homo sapiens" }
Ruby Foundations | 19
Variable Lookup
There are four types of variables in Ruby: global variables, class variables, instance
variables, and local variables.
Pages:
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44