Ruby Hash to array of values

RubyArraysHash

Ruby Problem Overview


I have this:

hash  = { "a"=>["a", "b", "c"], "b"=>["b", "c"] } 

and I want to get to this: [["a","b","c"],["b","c"]]

This seems like it should work but it doesn't:

hash.each{|key,value| value}
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]} 

Any suggestions?

Ruby Solutions


Solution 1 - Ruby

Also, a bit simpler....

>> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
>> hash.values
=> [["a", "b", "c"], ["b", "c"]]

Ruby doc here

Solution 2 - Ruby

I would use:

hash.map { |key, value| value }

Solution 3 - Ruby

hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]] 

Enumerable#collect takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.

The Enumerable module is pretty awesome. Knowing it well can save you lots of time and lots of code.

Solution 4 - Ruby

hash  = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]

Solution 5 - Ruby

It is as simple as

hash.values
#=> [["a", "b", "c"], ["b", "c"]]

this will return a new array populated with the values from hash

if you want to store that new array do

array_of_values = hash.values
#=> [["a", "b", "c"], ["b", "c"]]

array_of_values
 #=> [["a", "b", "c"], ["b", "c"]]

Solution 6 - Ruby

There is also this one:

hash = { foo: "bar", baz: "qux" }
hash.map(&:last) #=> ["bar", "qux"]

Why it works:

The & calls to_proc on the object, and passes it as a block to the method.

something {|i| i.foo }
something(&:foo)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontbrookeView Question on Stackoverflow
Solution 1 - RubyRay ToalView Answer on Stackoverflow
Solution 2 - RubyMichael DurrantView Answer on Stackoverflow
Solution 3 - RubyjergasonView Answer on Stackoverflow
Solution 4 - RubymrdedView Answer on Stackoverflow
Solution 5 - RubyMelissa QuinteroView Answer on Stackoverflow
Solution 6 - RubykarlingenView Answer on Stackoverflow