Hash from two arrays: Difference between revisions

→‎{{header|Ruby}}: Make pre-1.8.7 code work when key is an Array. Rename Array#to_hash to Array#zip_hash, so that Hash.try_convert(ary) never calls Array#to_hash by mistake.
(→‎{{header|Ruby}}: Make pre-1.8.7 code work when key is an Array. Rename Array#to_hash to Array#zip_hash, so that Hash.try_convert(ary) never calls Array#to_hash by mistake.)
Line 782:
<lang ruby>keys=['hal',666,[1,2,3]]
vals=['ibm','devil',123]
 
hash = Hash[keys.zip(vals)] # Ruby 1.8.7 and later
if RUBY_VERSION >= '1.8.7'
hash = Hash[*keys.zip(vals).flatten] # pre-1.8.7 (This only works if there are no arrays in the keys or data)
# Easy way, but needs Ruby 1.8.7 or later.
# now hash => {'hal' => 'ibm', 666 => 'devil', [1,2,3] => 123}
hash = Hash[keys.zip(vals)] # Ruby 1.8.7 and later
else
hash = {}
keys.each_index {|i| hash.store keys[i], vals[i] }
end
 
# nowp hash # => {'"hal' "=> '"ibm'", 666 => '"devil'", [1, 2, 3] => 123}
 
#retrieve the value linked to the key [1,2,3]
puts hash[ [1,2,3] ] # => 123</lang>
#123</lang>
 
Or define a new method in class Array:
2 Arrays can be merged into a hashmap as follows:
 
<lang ruby>
<lang ruby>class Array
def to_hashzip_hash(other)
Hash[ *(0...self.size()).inject([]) { |arr, ix| arr.push(self[ix], other[ix]) } ]
arr.push(self[ix], other[ix]) } ]
end
end
 
hash = %W{ a b c }.to_hashzip_hash( %W{ 1 2 3 } )
p hash # => {"a"=>"1", "b"=>"2", "c"=>"3"}</lang>
 
</lang> Reference from [http://programmingbulls.com/ruby-array-hash Ruby Array to Hash]
 
=={{header|Sather}}==
Anonymous user