Snippets
A couple of snippets for things I have to do a lot but forget how every once in a while

Using .map on a Hash

1
{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h
Copied!

Convert an Array of Hashes to a Hash

1
# I have an array of hashes
2
array = [ {id: 1, name: "test"} ]
3
4
# I want to turn it to a hash, where the key is `id`
5
array.map { |h| [h[:id], h] }.to_h
6
#=> { 1 => {:id => 1, :name => "test"} }
Copied!
Last modified 1yr ago