Sometimes you need to write a method accepts either a single item, or a list of items, and treats them the same way.

You could require callers to pass in a list every time, but that’s a bit unwieldy for the simple case:

def eat(food)
  food.each {|f| puts "mmm... #{f}!" }
end

eat ['an apple'] # I only want to eat one thing
                 # why do I need an array?

You could also check the argument type, and use an if statement to handle the single and list cases separately – but then you’d be duplicating the main logic!

def eat(food)
  if food.is_a?(Array)
    food.each {|f| puts "mmm... #{f}!" }
  else
    puts "mmm... #{food}"
  end
end

eat 'an apple'         # I can eat one thing...
eat ['soup', 'salad']  # or multiple things...
                       # but the logic is duplicated :(

The Array() method provides an elegant way to solve this problem. When you pass it a single item, it returns an array containing just that item. When you pass it an array, it simply returns the original array. Now you can treat the argument as an array, regardless of whether the caller passed an array or a single object:

def eat(food)
  Array(food).each {|f| puts "mmm... #{f}!" }
end

eat 'an apple'         # I can eat one thing...
eat ['soup', 'salad']  # or multiple things...
                       # using clean, simple code!

The next time your code needs to work with one or more items – try using Array()!