Railstic

sharing experiences

Recursive methods with block in Ruby

| Comments


def comic(cast)
   cast.each do |character|
      unless character.is_a?(Array)
         yield(character)
      else
     comic(character) {|x| yield x}
      end
   end
end

This method takes an array as argument and checks each element if it is an Array. If the element is not an Array then the block is called. If the element is an Array then the same method is called with that element as an argument and with the same block.


Now let’s look how we can call this method.

names = ['lucky luke', 'jolly jumper', 'rin tin tin', ['joe', 'william','jack', 'averell']]
comic(names) {|c| puts c}

Output :

lucky luke
jolly jumper
rin tin tin
joe
william
jack
averell

Comments