以散列值为条件数组的Ruby散列键。

时间:2021-08-24 21:17:17

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?

替代品吗?

2 个解决方案

#1


10  

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

Will do the same, but in more readable way.

将做同样的,但以更可读的方式。

#2


0  

You can also do

你也可以做

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

#1


10  

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

Will do the same, but in more readable way.

将做同样的,但以更可读的方式。

#2


0  

You can also do

你也可以做

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