DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Zip Two Arrays Together Into A Hash

06.21.2005
| 18662 views |
  • submit to reddit
        Found this here: 

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/122906
 
def Hash.from_pairs_e(keys,values)
  hash = {}
  keys.size.times { |i| hash[ keys[i] ] = values[i] }
  hash
end 
    

Comments

Snippets Manager replied on Tue, 2010/10/12 - 8:22am

seancribbs: Hash[*keys.zip(values).flatten] Consider what happens if some of the keys or values are arrays.

Snippets Manager replied on Thu, 2012/03/29 - 8:48am

Just Hash[[1,2,3].zip [9,8,7]] => {1=>9, 2=>8, 3=>7} and no monkey code

Snippets Manager replied on Mon, 2008/05/26 - 3:24pm

Urk. Didn't understand how to post code. From somewhere else, I have class Hash # # Create a hash from an array of keys and corresponding values. def self.zip(keys, values, default=nil, &block) hsh = block_given? ? Hash.new(&block) : Hash.new(default) keys.zip(values) { |k,v| hsh[k]=v } hsh end end Ex. hsh = Hash.zip([:foo, :bar, :baz], [1,2]) # => {:foo=>1, :baz=>nil, :bar=>2}

Snippets Manager replied on Mon, 2008/05/26 - 3:24pm

From somewhere else, I have class Hash # # Create a hash from an array of keys and corresponding values. def self.zip(keys, values, default=nil, &block) hsh = block_given? ? Hash.new(&block) : Hash.new(default) keys.zip(values) { |k,v| hsh[k]=v } hsh end end Ex. hsh = Hash.zip([:foo, :bar, :baz], [1,2]) # => {:foo=>1, :baz=>nil, :bar=>2}

Snippets Manager replied on Wed, 2006/03/29 - 10:25pm

How about this? (assume the arrays are of the same size) Hash[*keys.zip(values).flatten] The splat can be your friend!

Snippets Manager replied on Mon, 2012/05/07 - 2:12pm

no comment