2

I have an array,

array = [1,2,3]

Need to transform it to:

newArray = [{id: 1}, {id: 2}, {id: 3}]

I know this, Is there any efficient way?

array.each { |id| newArray << { id: id } }
0

2 Answers 2

5

Anything like this?

array.map { |id| Hash[:id, id] }

the same with hash literal

array.map { |id| { id: id } }
Sign up to request clarification or add additional context in comments.

Comments

0

A very elegant way:

  • convert to string
  • build the JSON style object
  • convert to array (inside the string)
  • let JSON parse it, for more (thread) safety
  • symbolize the keys, because in ruby it's preferred to use keys rather than strings

additionally you could use Base58 random key and hash it twice to mitigate timing attacks

  JSON.parse([1,2,3].map(&:to_s).collect{  "{\"id\": \"#{_1}\"}" }.join(",").prepend("[").concat("]")).collect(&:symbolize_keys)
=> [{:id=>"1"}, {:id=>"2"}, {:id=>"3"}]

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.