Coding is an Art

Anoiaque::Ergasterium

18/07/2010

Recursively chained send on an object with Array#inject

Suppose you have an arbitrery and dynamic list of methods to call on an object.
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 :

class Cat

  def drink_milk
    puts "I drink milk"
    self
  end

  def sleep
    puts "I sleep"
    self  
  end

  def climb_curtain
    puts "I climb the curtain"
    self  
  end

  def purr
    puts "Miaouu"
    self  
  end


  def do_these_things actions
    actions.inject(self) {|cat, action| cat.send(action)}
  end

end

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

Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it.
Alan Perlis


The best way to predict the future is to invent it.
Alan Kay


Ne découvre de nouvelles terres que celui qui sait quitter tout rivage.
André gide


Qui ne doute pas acquiert peu
Léonard de Vinci


Our life is frittered away by detail... simplify, simplify.
Henry David Thoreau