ruby使用transpose生成hash

irb(main):001:0> header = ['key1', 'key2', 'key3', 'key4']
=> ["key1", "key2", "key3", "key4"]
irb(main):002:0> values = ['val1', 'val2', 'val3', 'val4']
=> ["val1", "val2", "val3", "val4"]
irb(main):003:0>  [header, values].transpose
=> [["key1", "val1"], ["key2", "val2"], ["key3", "val3"], ["key4", "val4"]]
irb(main):004:0> transpose_array =  [header, values].transpose
=> [["key1", "val1"], ["key2", "val2"], ["key3", "val3"], ["key4", "val4"]]
irb(main):005:0> Hash[transpose_array]
=> {"key1"=>"val1", "key2"=>"val2", "key3"=>"val3", "key4"=>"val4"}
irb(main):006:0>

ref:

https://apidock.com/ruby/Array/transpose

http://railscasts.com/episodes/396-importing-csv-and-excel

Comments