Thursday, September 15, 2011

Converting Array to Hash

We can convert Array to Hash. Lets take an example.

a = ['a',1,'b',2,'c',3]

If we want to convert this array into has we can easily convert it to hash as follows:

h = Hash[*a]

It will result into
{"a"=>1, "b"=>2, "c"=>3}

Also if,

a = [["a",1],["b",2],["c",3]]

h = Hash[*a.flatten]

will result into
{"a"=>1, "b"=>2, "c"=>3}

No comments:

Post a Comment