rubymultidimensional-arrayhashruby-1.8.7

Transform 2D array into hash


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, ...}

Solution

  • [[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)]