18 Jun 2008, 23:17
Generic-user-small

James Whiteman (4 posts)

Hello, all.

Does anyone have a good explanation for this?


class Foo
end

Foo.instance_eval do
  def jump
    "jumping..." 
  end

  define_method(:shout) do
    "shouting..." 
  end
end

Foo.respond_to? :jump
  => true
Foo.respond_to? :shout
  => false
Foo.new.respond_to? :shout
  => true

It seems that define_method is pushing the method ‘shout’ into Foo’s own m_tbl instead of in the metaclass.
This was a little unexpected to me.

19 Jun 2008, 12:53
Dave_8_trans_72dpi_pragsmall

Dave Thomas (231 posts)

define_method always creates an instance method—now idea why, but it’s a deliberate decision of the implementers.

Dave

19 Jun 2008, 16:09
Generic-user-small

James Whiteman (4 posts)

Thanks, Dave—fantastic series by the way.

26 Dec 2008, 14:56
Generic-user-small

khaled alhabache (1 post)

You can bypass that by defining the method to your singleton class
smthing like :

class Object

def singleton_class 
  class << self
    self 
  end 
end

end

class Foo
end

Foo.singleton_class.class_eval do define_method(:shout) do “shouting…” end
end

puts Foo.respond_to? :shout #true

  You must be logged in to comment