I am trying to dynamically define methods on an initialized Ruby object MyObject
based on a hash my_hash
I pass to its initialize
method. In the body of the initialize
method, I have the following:
my_hash.each do |key|
class << self
define_method(key.underscore.to_sym) do
my_hash[key]
end
end
end
This fails with a undefined local variable or method 'key' for #<Class:#<MyObject:0x007fc7abw0cra0>>
. Any ideas why?
The my_hash
is made out of a json response with a lot of camelized keys, so it's more convenient to have simple ruby methods to get the values I want.