Trying to use define_method
inside initialize
but getting undefined_method define_method
. What am I doing wrong?
class C
You were almost there. Just point to the class with self.class
, don't even need to use :send
:
class C
def initialize(n)
self.class.define_method ("#{n}") { puts "some method #{n}" }
end
end
ob = C.new('new_method')
ob2 = C.new('new_method2')
# Here ob and ob2 will have access to new_method and new_method2 methods
You can also use it with :method_missing
to teach your class new methods like this:
class Apprentice
def method_missing(new_method)
puts "I don't know this method... let me learn it :)"
self.class.define_method(new_method) do
return "This is a method I already learned from you: #{new_method}"
end
end
end
ap = Apprentice.new
ap.read
=> "I don't know this method... let me learn it :)"
ap.read
=> "This is a method I already learned from you: read"