0

I'm fairly new to ruby and I've got a hash that looks like so:

{ ["key1", "key2"] => 5, ["key1", "key3"] => 2, ... }

and I would like to convert it to an array that looks something like

[ ["key1", "key2", 5], ["key1", "key3", 2] ... ]

How would I go about doing this?

3 Answers 3

3

Simply:

hash.collect{|k, v| k << v}

Of if you need the original hash unchanged:

hash.collect{|k, v| k + [v]}
Sign up to request clarification or add additional context in comments.

2 Comments

Your first one (or this version of it map { |k, v| k + [v] }) didn't mangle the original Hash's keys.
nit-picking: variable naming is very important. If you write k you're saying "singular/single-item". If write ks you are saying "plural/collection".
2

Another way could be:

hash.map(&:flatten)
# => [["key1", "key2", 5], ["key1", "key3", 2]]

Comments

-1

to_a does exactly that.

{ ["key1", "key2"] => 5, ["key1", "key3"] => 2}.to_a

1 Comment

No, look at the desired output: [ ["key1", "key2", 5], ["key1", "key3", 2] ... ].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.