Search code examples
rubyarrays

What's the best way to handle either a single value or an array in Ruby


I want to write a method that accepts either a single value or an array. What's the best idiom for doing this in Ruby?

Here are a couple things I've thought of:

def do_something(items)
  [*items].each { |item| ... }
end

I like the conciseness of that one, but it isn't clear unless you're used to this syntax

This next one just feels like too much code.

def do_something(items)
  items = [items] unless items.respond_to? :each
  items.each { |item| ... }
end

Solution

  • The Kernel#Array method works well here and is intended to be used to coerce things to an array:

    irb(main):001:0> def my_length(item_or_array)
    irb(main):002:1>   Array(item_or_array).length
    irb(main):003:1> end
    => nil
    irb(main):004:0> my_length('one')
    => 1
    irb(main):005:0> my_length([1, 2, 3])
    => 3