开发者

How can I grab certain values in a hash in Ruby?

开发者 https://www.devze.com 2023-01-12 20:37 出处:网络
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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号