user385948
user385948

Reputation: 909

How to create a hash with set of arrays

I have the following:

[[1,1,3], [1,2,3], [2,1,3]

I want to be able to take the above, and create a hash

 1 => { [1,3], [2,3] }, 2 => {[1,3]}

EDIT

Furthermore, I also wanted to add the following:

since the first element in the new array is the month, if I dont have data for the 4th month, it can default to [4,0]

 1 => { [1,3], [2,1], [3,4], }

Upvotes: 0

Views: 98

Answers (2)

tokland
tokland

Reputation: 67900

require 'facets'
xs = [[1,1,3], [1,2,3], [2,1,3]]
xs.map_by { |*ys| [ys.first, ys.drop(1)] }
=> {1=>[[1, 3], [2, 3]], 2=>[[1, 3]]}

Upvotes: 0

David
David

Reputation: 7303

x = [[1,1,3], [1,2,3], [2,1,3]]
y = x.map {|a| {a[0]=> [a[1], a[2]]}}

Edit

Actually my initial solution was wrong, it gives you:

[{1=>[1, 3]}, {1=>[2, 3]}, {2=>[1, 3]}] 

I believe this is closer to what you were looking for:

x = [[1,1,3], [1,2,3], [2,1,3]]
h = {}

x.each do |a|
  if h[a[0]].nil?
    h[a[0]] = []
  end
  h[a[0]] << [a[1], a[2]]
end

Which gives you a hash of arrays:

{1=>[[1, 3], [2, 3]], 2=>[[1, 3]]}

Upvotes: 4

Related Questions