Ruby /
Metaprogramming /
Dynamics of Methods
С помощью define_method можно определять методы во время выполнения программы -
class Animal
%w[dog cat bird].each do |animal|
define_method("speak_#{animal}") do
puts "The #{animal} says: #{animal == 'dog' ? 'Woof!' : animal == 'cat' ? 'Meow!' : 'Tweet!'}"
end
end
end
pet = Animal.new
pet.speak_dog # => The dog says: Woof!
pet.speak_cat # => The cat says: Meow!
pet.speak_bird # => The bird says: Tweet!
А с помощью send можно вызывать методы -
class Animal
attr_accessor :gender
end
pet = Animal.new
pet.send(:gender=, "male") # => male
pet.send("gender") # => male