Ruby 哈希白名单过滤器 [英] Ruby Hash Whitelist Filter
本文介绍了Ruby 哈希白名单过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图弄清楚如何将键和值对从一个过滤器过滤到另一个过滤器中
I am trying to figure out how I can filter out key and value pairs from one filter into another
例如我想取这个哈希
x = { "one" => "one", "two" => "two", "three" => "three"}
y = x.some_function
y == { "one" => "one", "two" => "two"}
感谢您的帮助
可能应该提到,在这个例子中,我希望它充当白名单过滤器.也就是说,我知道我想要什么,而不是我不想要什么.
should probably mention that in this example, I want it to behave as a whitelist filter. That is, I know what I want, not what I don't want.
推荐答案
也许这就是你想要的.
wanted_keys = %w[one two]
x = { "one" => "one", "two" => "two", "three" => "three"}
x.select { |key,_| wanted_keys.include? key }
包含在例如 Enumerable mixin 中.Array 和 Hash 提供了很多有用的方法,例如 select/reject/each/etc.. 我建议您使用 ri Enumerable 查看它的文档.
The Enumerable mixin which is included in e.g. Array and Hash provides a lot of useful methods like select/reject/each/etc.. I suggest that you take a look at the documentation for it with ri Enumerable.
这篇关于Ruby 哈希白名单过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文