I use a lot of iterations to define convenience methods in my models, stuff like:
PET_NAMES.each do |pn|
define_method(pn) do
...
...
end
but I’ve never been able to dynamically define setter methods, ie:
def pet_name=(name)
...
end
using define_method like so:
define_method("pet_name=(name)") do
...
end
Any ideas? Thanks in advance.
Here’s a fairly full example of using
define_methodin a module that you use to extend your class:Output:
You were close, but you don’t want to include the argument of the method inside the arguments of your call to
define_method. The arguments go in the block you pass todefine_method.