How to convert an array of ids to array of hash with a key in ruby?

Viewed 198

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 } }
2 Answers

Anything like this?

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

the same with hash literal

array.map { |id| { id: id } }

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"}]
Related