teohm.dev

I enjoy life, and make stuff for people I care about :)

Ruby Idiom to Ensure Variable Is Array

Stop doing this:

1
2
3
4
5
6
arry = input || []  # handle input == nil
arry = [input] unless arry.kind_of?(Array)  # handle single value object

arry.each do |item|
  #process item
end

In Ruby, you should use Kernel#Array to convert the variable into an array object:

1
2
3
4
5
6
7
Array(input).each do |item|
  # process item
end

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

More usage examples written in minitest.

Comments