Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Hash to array of arrays in ruby

Let's say i have a hash

 {:facebook=>0.0, :twitter=>10.0, :linkedin=>6.0, :youtube=>8.0}

Now i want it to change to an array like

[[Facebook,0.0],[Twitter,10.0],[Linkedin,6.0],[Youtube,8.0]]

I can use a logic to extract and change it in to array, but i was just wondering if there could be any defined methods in ruby which i can use to implement the above.

like image 586
Bijendra Avatar asked Oct 14 '11 10:10

Bijendra


2 Answers

You can use to_a.

{:facebook=>0.0, :twitter=>10.0, :linkedin=>6.0, :youtube=>8.0}.to_a

returns

[[:facebook, 0.0], [:twitter, 10.0], [:linkedin, 6.0], [:youtube, 8.0]] 

This won't automatically convert your symbols to constants though, you will have to use map (and const_get) for that.

{:facebook=>0.0, :twitter=>10.0, :linkedin=>6.0, :youtube=>8.0}.map{|k,v| [Kernel.const_get(k.to_s.capitalize), v]}

Outputs

[[Facebook,0.0],[Twitter,10.0],[Linkedin,6.0],[Youtube,8.0]]
like image 197
Gazler Avatar answered Oct 04 '22 21:10

Gazler


your_hash.to_a

is the answer. http://www.ruby-doc.org/core-1.9.2/Enumerable.html#method-i-to_a

like image 39
bricker Avatar answered Oct 04 '22 22:10

bricker