12

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.

4 Answers 4

32

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]]
Sign up to request clarification or add additional context in comments.

Comments

7

your_hash.to_a

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

Comments

6

Just wrap your hash in [] and add asterisks before hash.

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

1 Comment

I think that this is kinda crypt solution. Calling to_a is much more readable :)
5
sites = {:facebook => 0.0, :twitter => 10.0, :linkedin => 6.0, :youtube => 8.0}
sites.map { |key, value| [Object.const_get(key.to_s.capitalize), value] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.