Anonymous user
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'
# Easy way, but needs Ruby 1.8.7 or later.
# now hash => {'hal' => 'ibm', 666 => 'devil', [1,2,3] => 123}▼
else
hash = {}
keys.each_index {|i| hash.store keys[i], vals[i] }
end
#retrieve the value linked to the key [1,2,3]
puts hash[ [1,2,3] ] # => 123</lang>
Or define a new method in class Array:
<lang ruby>class Array
def
Hash[
arr.push(self[ix], other[ix]) } ]
end
end
hash = %W{ a b c }.
p hash # => {"a"=>"1", "b"=>"2", "c"=>"3"}</lang>
=={{header|Sather}}==
|