关于ruby的哈希白名单过滤器的问题?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (14)

我正试图弄清楚如何将键和值对从一个筛选器过滤到另一个筛选器中。

例如,我想拿这个哈希

x = { "one" => "one", "two" => "two", "three" => "three"}

y = x.some_function

y == { "one" => "one", "two" => "two"}

提问于
用户回答回答于

wanted_keys = %w[one two]
x = { "one" => "one", "two" => "two", "three" => "three"}
x.select { |key,_| wanted_keys.include? key }

包含在Array和Hash中的Enumerable mixin提供了很多有用的方法,比如select/reject/each/等。

用户回答回答于

Rails的ActiveSupport库也提供切片,尤其是密钥级别处理哈希:

y = x.slice("one", "two") # => { "one" => "one", "two" => "two" }
y = x.except("three")     # => { "one" => "one", "two" => "two" }
x.slice!("one", "two")    # x is now { "one" => "one", "two" => "two" }

扫码关注云+社区