0

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 } }  
2
  • 4
    Your code is great, it is short, easy to read and to understand. What would you consider "better"? Shorter? Faster? Commented Nov 2, 2022 at 8:48
  • wondering if there is a more concise way of writing what I did - maybe a hidden Ruby method that I'm not aware of :) Commented Nov 2, 2022 at 9:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Or hash shorthand introduced in Ruby 3.1: names.map { |name| { name: } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.