0

Given this array:

array = ['one', 'two']

what is the best way to turn that into something like the following?

[{value: 'one', label: 'one'}, {value: 'two', label: 'two'}]

2 Answers 2

6

Use Array#map, which iterates over your collection and returns an array. In your case, just return the hash directly

array.map { |a| {value: a, label: a} }
# => [{:value=>"one", :label=>"one"}, {:value=>"two", :label=>"two"}]
Sign up to request clarification or add additional context in comments.

Comments

1

The best way is Array#map, but just to try a different way check also Enumerable#each_with_object:

array = ['one', 'two']
array.each_with_object([]) { |e, a| a << {value: e, label: e} }
#=> [{:value=>"one", :label=>"one"}, {:value=>"two", :label=>"two"}]

Comments

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.