These methods break encapsulation, so use
them with care.
class C
def initialize
@ivar = 1
end
end
c = C.new
c.instance_variables # => ["@ivar"]
c.instance_variable_get(:@ivar) # => 1
c.instance_variable_set(:@ivar, 3) # => 3
c.instance_variable_get(:@ivar) # => 3
Metaprogramming Techniques | 29
The Object#methods method returns an array of instance methods, including singleton
methods, defined on the receiver. If the first parameter to methods is false, only
the object??™s singleton methods are returned.
class C
def inst_method
end
def self.cls_method
end
end
c = C.new
class << c
def singleton_method
end
end
c.methods - Object.methods # => ["inst_method", "singleton_method"]
c.methods(false) # => ["singleton_method"]
Module#instance_methods returns an array of the class or module??™s instance methods.
Note that instance_methods is called on the class, while methods is called on an
instance. Passing false to instance_methods skips the superclasses??™ methods:
C.instance_methods(false) # => ["inst_method"]
We can also use Metaid??™s metaclass method to examine C??™s class methods:
C.metaclass.instance_methods(false) # => ["new", "allocate", "cls_method",
"superclass"]
In my experience, most of the value from these methods is in satisfying curiosity.
With the exception of a few well-established idioms, there is rarely a need in production
code to reflect on an object??™s methods.
Pages:
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59