tbrooke
tbrooke

Reputation: 2197

Ruby Hash to array of values

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?

Upvotes: 153

Views: 229388

Answers (6)

karlingen
karlingen

Reputation: 14645

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)

Upvotes: 3

Melissa Quintero
Melissa Quintero

Reputation: 191

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"]]

Upvotes: 12

mrded
mrded

Reputation: 5320

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

Upvotes: 8

Michael Durrant
Michael Durrant

Reputation: 96614

I would use:

hash.map { |key, value| value }

Upvotes: 52

Jamison Dance
Jamison Dance

Reputation: 20184

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.

Upvotes: 24

Ray Toal
Ray Toal

Reputation: 88478

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

Upvotes: 300

Related Questions