The easiest way to convert any value to Array in Ruby

Subscribe to receive new articles. No spam. Quality content.

Ruby is not a strong typed programming language, so methods can accept arguments of any type. But sometimes we want to make sure that value we accept is an Array.

I've seen many times that developers do something like that:

def initialize(items)
  @items = items.is_a?(Array) ? items : [items]
  ...
end

This code makes sure that @items will be an Array, even if items was a single item. First of all, it's not good that some part of an application calls this method with a single value, and another part passes an Array. Probably you should pass an array every time.

But sometimes that happens and we need to convert single value to Array. In that case it's much easier to use this approach:

def initialize(items)
  @items = Array(items)
  ...
end

If items is an Array - it will remain the same, but if it's a single value, it will be wrapped into Array.

Even if items is nil it will be converted to a blank Array. Very useful and short version of conversion to array.

Couple more examples

Array(nil) # => []
Array([1,2,3]) # => [1,2,3]
Array(1) # => [1]

Happy hacking!

Subscribe to receive new articles. No spam. Quality content.

Comments