af83

Ruby tricks: Array syntax

How many times have you seen those ruby code examples?

if my_array.present?
  my_array
else
  []
end

# Or the ternary version:
my_array.present? ? my_array : []

# Or even the 'or' version:
my_array || []

In those examples, a presence check is made on my_array, otherwise, it will return an empty list. It's valid ruby code, but there's a simpler way to achieve that:

# Just:
Array(my_array)

With nil or an empty array, Array will return an empty array, and with an array of values, it will return the same array of values.

It can also be used if you don't know if you have only one item or an array. This syntax removes useless verifications, and always returns an array.

Another nice trick is about each and map (and theirs aliases).

# Calling save on all items in this collection
collections.each do |item|
  item.save
end

The same result can be achieved this way :

# Calling save on all items in this collection
collections.each &:save

blog comments powered by Disqus