简体   繁体   English

Ruby哈希键以数组为条件的哈希值

[英]Ruby hash keys to array conditional on hash value

I would like to extract hash key values to an array when a condition is met. 我希望在满足条件时将哈希键值提取到数组。 For example, with hash h I want to extract the keys where the values are "true": 例如,使用散列h我想提取值为“true”的键:

h = { :a => true, :b => false, :c =>true }

I've come up with this: 我想出来了:

h.map {|k,v| k if v==true} - [nil]

Any alternatives? 任何替代品?

h.select { |_, v| v }.keys

将采用相同的方式,但更具可读性。

You can also do 你也可以

s = {}
h.each do |k,v|
   s[k] = v if v==true
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM