Ruby
A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.
Some of the samples which in found in net for converting a Array to Hash
Aray to Hash
require "enumerator"
class Array
def to_h
Hash[*enum_with_index.to_a.flatten]
end
end
%w{a b c d}.to_h # => {"a"=>0, "b"=>1, "c"=>2, "d"=>3}
class Array
def to_h(keys)
Hash[*keys.zip(self).flatten]
end
end
a=['1','2','3']
b=['4','5','6']
a.to_h(b)=>{"6"=>"3", "4"=>"1", "5"=>"2"}
a = [1, 2, 3]
Hash[*a.collect { |v| [v, v*2]}.flatten]
=> {1=>2, 2=>4, 3=>6}
class << Hash
def create(keys, values)
self[*keys.zip(values).flatten]
end
end
>> Hash.create(['a', 'b', 'c'], [1, 2, 3])
=> {"a"=>1, "b"=>2, "c"=>3}
a = [1,2,3]
ReplyDelete( 0...a.size ).to_a.zip( a ).inject({}) { |h,x| h[x[0]]=x[1]; h }
thanks for ur reply
ReplyDelete