Home > Back-end >  Convert an Array of Strings into an Array of Hashes with same key
Convert an Array of Strings into an Array of Hashes with same key

Time:11-02

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? By current approach is as follows, but knowing Ruby, there must be something better:

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

CodePudding user response:

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.

  •  Tags:  
  • ruby
  • Related