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
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.
Subscribe to:
Post Comments (Atom)
2 comments:
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
that is very true. ha... maybe my example was not the best, but you get the point...
Post a Comment