Thursday, March 8, 2007

Using Ruby flatten and to_a

class Processor
  def initialize arg
  @arg = arg
  end
 def process
  puts @arg
 end
end

def run_single(processor)
 processor.process
end

def run(processors)
 processors.each{|p| p.process}
end

run_single(Processor.new 'Hello')
run([Processor.new 'Hello',Processor.new 'World'])
In above example, we need to define two methods run_single taking a processor and run taking array of processors. To make it simple, we can remove run_single method just call
run([Processor.new 'Hello']) 
in case of single processor. However passing a single element array seems to be not natural, by using flatten or to_a we can create a method that accept both element and array of element as parameter
def run(processor)
 [processor].flatten.each{|p| p.process }
end
or other possible way is
def run(processor)
 processor.to_a.each{|p| p.process }
end
then we can do
run(Processor.new 'Hello')
run([Processor.new 'Hello',Processor.new 'World'])

No comments: