1

Here is an example:

class MyClass
end

obj = MyClass.new
obj.instance_eval do
  def hello
    "hello"
  end
end

obj.hello
# => "hello"

obj.methods.grep "hello"
# => ["hello"]

MyClass.instance_methods.grep "hello"
# => []

MyClass's instance methods don't contain 'hello' method, so My question is where Ruby stores the method defined in instance_eval()?

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
Rambo
  • 1,834
  • 2
  • 13
  • 10

1 Answers1

2

Look at this:

obj = MyClass.new
def obj.hello
  "hello"
end

obj.hello #=> "hello"
obj.singleton_methods #=> [:hello]
obj.methods.grep :hello #=> [:hello]

obj.instance_eval do
  def hello2 ; end
end #

obj.singleton_methods #=> [:hello, :hello2]

As you can see instead of using instance_eval you can also define a method directly on an object. In both cases they end up in the object's singleton class (eigenclass), which can be accessed via obj.singleton_class in Ruby 1.9 and the class << self ; self; end idiom in Ruby 1.8.

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158