Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想在满足条件时将哈希键值提取到数组中。例如,使用 hash h 我想提取值为“true”的键:
h = { :a => true, :b => false, :c =>true }
我想出了这个:
h.map {|k,v| k if v==true} - [nil]
有什么选择吗?
h.select { |_, v| v }.keys
将做同样的事情,但以更具可读性的方式。
你也可以做
s = {} h.each do |k,v| s[k] = v if v==true end