Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash of arrays from array

Tags:

arrays

ruby

hash

I have the following array

a=[["kvm16", "one-415"], ["kvm16", "one-416"], ["kvm5", "one-417"]]

I would like to convert this to a hash that looks like this

{"kvm5"=>["one-417"], "kvm16"=>["one-417", "one-416"]}

everything I have tried squashes the value.

v=Hash[ a.collect do |p| [p[0], [ p[1] ] ] end ]
=> {"kvm5"=>["one-417"], "kvm16"=>["one-416"] }

I was thinking I could check to see if v[p[0]] is an array, but the variable isn't defined inside this block.

Is there a clean way to accomplish what I am looking for?

like image 646
J.T. Avatar asked Apr 07 '26 18:04

J.T.


1 Answers

Yeah, you have to do it yourself, I'm afraid.

a = [["kvm16", "one-415"], ["kvm16", "one-416"], ["kvm5", "one-417"]]

h = a.each_with_object({}) do |(k, v), memo|
  (memo[k] ||= []) << v
end

h # => {"kvm16"=>["one-415", "one-416"], "kvm5"=>["one-417"]}

Or, if you're on older ruby (1.8.x):

h = {}
a.each do |k, v|
  (h[k] ||= []) << v
end

h # => {"kvm16"=>["one-415", "one-416"], "kvm5"=>["one-417"]}
like image 92
Sergio Tulentsev Avatar answered Apr 09 '26 12:04

Sergio Tulentsev