How to ensure a variable is an array in Ruby
While developing active_model_pusher I had to dive into the pusher-gem
source code.
Seeing the following code reminded me that not all developers know about a useful trick that makes it easy to ensure a variable is an array.
Here's the offending code:
# lib/pusher/client.rb
def trigger_params(channels, event_name, data, params)
channels = [channels] if channels.kind_of?(String)
# ..
end
Instead of doing this check for Strings specifically, you can ensure your variable will be an array by calling Array(variable). Here's how the refactored code will look:
channels = Array(channels)
There is one case you should be aware of:
Array({key: :value}) # [[:key, :value]]
If you don't want you hash to be converted to an array and you are using Rails, there is an almost identical method Array.wrap method, which behaves a bit differently:
Array.wrap({key: :value}) # [{key: :value}]
You can read about more differences between Array() and Array.wrap() in the documentation
You're the 9935th person to read this article.