turning a hash into an array

D

David Garamond

While reading the archives, I found out about this cool "idiom":

hash = Hash[*ary]

which will turn [1,2,3,4] into {1=>2, 3=>4}. Is there anything similar
to do the opposite (i.e., turn {1=>2, 3=>4} into [1,2,3,4] or
[3,4,1,2])? I can only come up with this:

ary = Hash.to_a.flatten
 
P

Phil Tomson

While reading the archives, I found out about this cool "idiom":

hash = Hash[*ary]

which will turn [1,2,3,4] into {1=>2, 3=>4}. Is there anything similar
to do the opposite (i.e., turn {1=>2, 3=>4} into [1,2,3,4] or
[3,4,1,2])? I can only come up with this:

ary = Hash.to_a.flatten

Well this is something I didn't know about till I saw Matz mention it in
another thread today:

irb(main):010:0> obj = {'a' => 1, 'b' => 2}
=> {"a"=>1, "b"=>2}
irb(main):011:0> Array(obj)
=> [["a", 1], ["b", 2]]

Now you could flatten it:

irb(main):012:0> Array(obj).flatten
=> ["a", 1, "b", 2]


Phil
 
R

Robert Klemme

David Garamond said:
While reading the archives, I found out about this cool "idiom":

hash = Hash[*ary]

which will turn [1,2,3,4] into {1=>2, 3=>4}. Is there anything similar
to do the opposite (i.e., turn {1=>2, 3=>4} into [1,2,3,4] or
[3,4,1,2])? I can only come up with this:

ary = Hash.to_a.flatten

You can use inject if you want to save the intermediate array:

irb(main):050:0> h=Hash[1,2,3,4]
=> {1=>2, 3=>4}
irb(main):051:0> h.inject([]){|arr,(key,val)| arr << key << val}
=> [1, 2, 3, 4]

Regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top