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.
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]]
your_hash.to_a
is the answer. http://www.ruby-doc.org/core-1.9.2/Enumerable.html#method-i-to_a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With