Topic: Quick Tip: One for all and all for One!

I just converted a method that used to take (among other arguments) one id in aparamter and do a bunch of stuff lookups and computations and (gasp) return some result. 

Next thing I know is that I really need another method just like that one, that does it's thing for an entire list of id's.  Here is one thing I did to simplify my code and use just a single method than can handle either a single id, or an array of ids:

def big_method(id_or_ids, other, args, here)

  ids = [id_or_ids].flatten


I know you it's kind of a yawner, but it beats doing things like this:
  if id_or_ids.kind_of?(Array)
    ids = id_or_ids
    ids = [ id ]

Anyhow -- once you got "ids", you know it's an array, and you can convert the entire method to just work on the array.  Ok ok ... I'm just still excited by ruby is all.

Re: Quick Tip: One for all and all for One!

Cool. I've seen this done in the Rails source a slightly different way:

def big_method(id, other, args, here)
  if id.kind_of? Array
    id.collect { |id| big_method(id, other, args, here) }
    # process single id

In this case it repeats the call for each item in the array if an array is given. One advantage to this is it returns the responses in an array if an array is given, but just returns the response normally if no array is given.

Railscasts - Free Ruby on Rails Screencasts

Re: Quick Tip: One for all and all for One!

OOoo seski! smile  Thanks!
Of course in my case -- I actually don't want to return an array, but a cumulative something.  For example a graph that can handle showing information about 1 user, or N users -- either case I still just want 1 graph. 

But that other way is definately something to keep in mind!

Last edited by Slurpy (2007-03-15 16:15:56)