Array to Hash in Ruby
To be able to converting hash into array in Ruby is easy but how do we convert an array into a hash? This tutorial did the ruby array to hash trick.
RUBY:
class Array
def to_hash(other)
Hash[ *(0...self.size()).inject([]) { |arr, ix| arr.push(self[ix], other[ix]) } ]
end
end
%W{ a b c }.to_hash( %W{ 1 2 3 } )
#=> {"a"=>"1", "b"=>"2", "c"=>"3"}
If you are looking to wonder what hash map is, check out this Ruby Hash.
- Log in to post comments