For example you have Cat class with methods :
#drink_milk
#sleep
#climb_curtain
#purr
And you want a method taking an arbitrery list of actions to execute as parameter.
With powerful inject method ... so easy to do :
"I drink milk"
self
end
puts "I sleep"
self
end
puts "I climb the curtain"
self
end
puts "Miaouu"
self
end
actions.inject(self) {|cat, action| cat.send(action)}
end
end
puts
cat = Cat.new
cat.do_these_things [:sleep, :drink_milk] # => I sleep I drink milk
cat.do_these_things [:purr, :drink_milk, :climb_curtain] # => Miaouu I drink milk I climb the curtain
Aucun commentaire:
Enregistrer un commentaire