Thursday, October 23, 2008

Method of the Day: Array()

Another oldy but a goodie... Array() wraps its parameter in an array. If it's already an array, it just returns it. If it's nil, it returns an empty array. It's super useful when you want to write a method that can take a single instance of an object or an array of objects.
Array(nil) => []
Array([]) => []
Array(1) => [1]
Array([1]) => [1]

def do_stuff(model_or_models)
  models = Array(model_or_models)
  models.each do |model|
    # do stuff...
  end
end

2 comments:

nakajima said...

Hey, you could also use a splat args for that do_stuff method:

def do_stuff(*args)
args.each do |model|
# do stuff...
end
end

Ben said...

that is very true. ha... maybe my example was not the best, but you get the point...