How can I grab certain values in a hash in Ruby?
I have a hash
hash = { 1=> { 0=> 'apple', 1=> 'tree'... ....}, 2=> {.....}}
I want to grab the 0 for all hashes within the hash. I know there is a transpose for a开发者_运维百科rray, but there any way to do this with a hash easily?
Something like this should work:
hash.values.collect{|v| v[0]}
Example:
irb(main):001:0> hash = { 1 => { 0 => 'apple', 1 => 'tree' },
2 => { 0 => 'foo', 1 => 'bar' }}
=> {1=>{0=>"apple", 1=>"tree"}, 2=>{0=>"foo", 1=>"bar"}}
irb(main):002:0> hash.values.collect{|value| value[0]}
=> ["apple", "foo"]
精彩评论