1
I was researching on the internet how to create methods dynamically in Ruby and in some forums in English, people spoke to use the method define_method
, passing a name to the method and a &block which would be the body of this method. I tried to do this but it does not create the method for me.
See the code below:
class Cachorro
define_method :falar do
puts "Au au!"
end
def method_missing(method_name,*args)
if method_name == :andar
define_method :andar do
puts "Andando..."
end
end
end
end
animal = Cachorro.new
animal.falar
animal.andar
In this code, the method falar
but the andar
no. Why does this happen ? What is the right way to use the method define_method
?
And taking advantage of the fact that I’m talking about dynamically creating methods in Ruby, there’s some way to dynamically create attributes like this: animal.nome = 'Bidu'
?
Finally someone answered me kkk. Thank you, it helped a lot!
– JeanExtreme002