Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SQL result to hash with ID keys with Ruby

Tags:

ruby

I have the following array (SQL result):

[
  {:id => 1, :field1 => "one", :field2 => "two"},
  {:id => 2, :field1 => "one", :field2 => "two"},
  ...
]

What I want is:

{
  1 => {:field1 => "one", :field2 => "two"},
  2 => {:field1 => "one", :field2 => "two"},
  ...
}

Now I do like the following:

data = {}
result.each do |row|
  data[row[:id]] = {:field1 => row[:field1], :field2 => row[:field2]}
end

I'm absolutely sure that's wrong way. What is the best way to do it with Ruby? Is there are any snippet like map or something else?

like image 685
odiszapc Avatar asked Mar 12 '26 00:03

odiszapc


2 Answers

Hash[arr.map { |h| [h.delete(:id), h] }]
like image 129
hs- Avatar answered Mar 14 '26 16:03

hs-


One line :)

hash = arr.clone.each_with_object({}) { |e,res| res[e.delete(:id)] = e }

clone is for not destroying arr variable

like image 22
megas Avatar answered Mar 14 '26 17:03

megas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!