23 June 2009

Converting an array of tuples to a hash

I was working with a class today that gave me an array of tuples:

1 person = [['name','craig'],['likes','climbing']]

I want to use this data to create an object so my code would be much prettier if I had a hash.

I thought converting this array of tuples to a hash would be messy but it’s not. You can create a hash from an array like so.

1 >> Hash['name','craig','likes','climbing']
2 => {"name"=>"craig", "likes"=>"climbing"}

Now that we know that, we can create a hash from an array of tuples.

1 >> tuples = [['name','craig'],['likes','climbing']]
2 => [["name", "craig"], ["likes", "climbing"]]
3 >> Hash[*tuples.flatten]
4 => {"name"=>"craig", "likes"=>"climbing"}