class Array # Converts a two-element associative array into a hash. # # a = [ [:a,1], [:b,2] ] # a.to_h #=> { :a=>1, :b=>2 } # # If +arrayed+ is set it will maintain trailing arrays. # # a = [ [:a,1,2], [:b,3] ] # a.to_h(true) #=> { :a=>[1,2], :b=>[3] } # # NOTE: the use of a values parameter has been deprecated # because that functionality is as simple as: # # array1.zip(array2).to_h # def to_h(arrayed=nil) unless arrayed Hash[*self.flatten] else h = {} each{ |e| h[e.first] = e.slice(1..-1) } h end end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TCArray < Test::Unit::TestCase def test_to_h_1 k = [1,3,5] v = [2,4,6] assert_equal( { 1=>2, 3=>4, 5=>6 }, k.zip(v).to_h ) end def test_to_h_2 a = [[1,2],[3,4],[5,6]] assert_equal( { 1=>2, 3=>4, 5=>6 }, a.to_h ) end end =end