1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00
Files
til/ruby/wrap-things-in-an-array-even-hashes.md

791 B

Wrap Things In An Array, Even Hashes

I've always used Kernel::Array to wrap things in an array. It works great.

> Array(nil)
#=> []
> Array(1)
#=> [1]
> Array(["hello", "world"])
#=> ["hello", "world"]

Except with hashes, it might not do what you expect when given a hash.

> Array({a: 1, b: 2})
#=> [[:a, 1], [:b, 2]]

I just wanted the hash wrapped in an array, not turned into an array of tuples.

The Array class has a method #wrap which behaves similarly to Kernal::Array while also handling hashes in the way I was wanting.

> Array.wrap(nil)
#=> []
> Array.wrap(1)
#=> [1]
> Array.wrap(["hello", "world"])
#=> ["hello", "world"]
> Array.wrap({a: 1, b: 2})
#=> [{a: 1, b: 2}]

source