红宝石哈希白名单过滤器 [英] Ruby Hash Whitelist Filter
问题描述
我试图弄清楚如何将一个过滤器中的键和值对过滤到另一个过滤器中。例如,我想把这个哈希值放在
x = {one=> one,two=> two,three=> three}
y = x.some_function
y == {one=> one,two=> two}
感谢您的帮助
<编辑:应该提到,在这个例子中,我希望它表现为白名单过滤器。也就是说,我知道我想要的是什么,而不是我不想要的。 / p>
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 /等。我建议你用ri Enumerable来看看它的文档。
I am trying to figure out how I can filter out key and value pairs from one filter into another
For example I want to take this hash
x = { "one" => "one", "two" => "two", "three" => "three"}
y = x.some_function
y == { "one" => "one", "two" => "two"}
Thanks for your help
EDIT: 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.
Maybe this it what you want.
wanted_keys = %w[one two]
x = { "one" => "one", "two" => "two", "three" => "three"}
x.select { |key,_| wanted_keys.include? key }
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.
这篇关于红宝石哈希白名单过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!