I have code in a class that dynamically creates methods using
["bar", "baz"].each do |method|
`create_method' for Foo:Class (NoMethodError)
There are several problems with your code. The error you are getting has absolutely nothing to do with
public at all. The error message says that the method
create_method cannot be found. There are two reasons for that:
create_methodafter its definition.
create_methodis defined as an instance method, i.e. for calling it on instances of
Foo, but you are calling it on
Fooitself. You have to define it as a method somewhere in
Foo's class (i.e.
Class), one of its ancestors (e.g.
Foo's singleton class.
I will define it as a singleton method of
Foo here, but if the method really is as generic as you have showed in your example, then it probably rather belongs in
class Foo class << self private def create_method(name) define_method(name) do puts "HELL" end end end ["bar", "baz"].each do |method| create_method(method) end end Foo.new.bar # HELL