From: Robert Klemme Date: 2010-09-08T16:09:55+09:00 Subject: Re: Receiving array naturally? On Wed, Sep 8, 2010 at 7:10 AM, Terry Michaels wrote: > As I learn Ruby, I find a lot of flexibility in the syntax. I was > thinking there was a way to do something like so: Say I had a method > that would receive an array. Is it possible to define the method so that > it can take the array elements /either/ as an Array object, /or/ as a > comma-separated (variable) list of elements (without the brackets)? > > Like, > >  process_data(string1, string2, string3, ...) > > would be the same as > >  string_array = [string1, string2, string3, ...] >  process_data(string_array) > > I thought something like so would work: > >  def process_data(*strings) >     ... >  end > > That works with the comma-separated list, because the list gets combined > into one array ("strings"), but if I pass in an array object, that array > object is not split up, but rather becomes one (Array object) element of > the "strings" array. > > Do I need to write code that checks whether each object passed in is an > array or not, manually splitting if necessary (which perhaps is > complicated) or is there something else I'm overlooking? Or perhaps is > my whole idea dumb from the start...? I wouldn't judge on this one although I generally believe that reduction of alternatives increases clarity. You could do def simple(*a) a.flatten.each do |x| x.whatever end end def complex(*a) if a.length == 1 && Enumerable === a.first a.first else a end.each do |x| x.whatever end end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/