Naoki Mi
Naoki Mi

Reputation: 27

Convert an Array of Strings into an Array of Hashes with same key

I have an array of strings:

names = ['Caitlyn', 'Jayce', 'Jinx', 'Vi']

and my goal is to create several instances and once from this array:

Champion.create!([{ name: 'Caitlyn'}, { name: 'Jayce'}, { name: 'Jinx'}, { name: 'Vi']})

What would be the best way for getting from the array of strings to the array of hashes? My current approach is as follows, but knowing Ruby, there must be something better:

names.map { |name| { name: name } }  

Upvotes: 0

Views: 63

Answers (1)

spickermann
spickermann

Reputation: 106792

The only way I can think of to make this even shorter would be using numbered block parameters which were introduced int Ruby 2.7.

names = ['Caitlyn', 'Jayce', 'Jinx', 'Vi']
names.map { { name: _1 } }
#=> [{:name=>"Caitlyn"}, {:name=>"Jayce"}, {:name=>"Jinx"}, {:name=>"Vi"}]
                                          

But I am not sure if this improves readability.

Upvotes: 3

Related Questions