1

I have a sorted 2D array as follows:

a = [[1, 2011], [3, 1999], [4, 2014], [6, 1998], ...]

How can I transform this into a hash with the key being the year and the value being the number in front?

{2011 => 1, 1999 => 3, 2014 => 4, 1998 => 6, ...}
Stefan
  • 109,145
  • 14
  • 143
  • 218
Alan1
  • 83
  • 1
  • 4

3 Answers3

3
[[1, 2011], [3, 1999], [4, 2014], [6, 1998]].map(&:reverse).to_h
  # => {2011=>1, 1999=>3, 2014=>4, 1998=>6}

For older versions of Ruby, you could use:

Hash[a.map(&:reverse)]
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
1

Here are a couple of other ways that should be 1.8.7-friendly:

a = [[1, 2011], [3, 1999], [4, 2014], [6, 1998]]

v, y = a.transpose
Hash[y.zip(v)]
  #=> {2011=>1, 1999=>3, 2014=>4, 1998=>6}

a.reduce({}) { |h,(v,y)| h.update({ y=>v }) }
  #=> {2011=>1, 1999=>3, 2014=>4, 1998=>6}

Hash#update (aka merge!) could be replaced with Hash#merge.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

Here is one more way.

a.each.with_object({}) {|(v,k), h| h[k] = v}
Wand Maker
  • 18,476
  • 8
  • 53
  • 87