我试图找出如何将键和值对从一个过滤器过滤到另一个过滤器
例如,我想采取这个哈希
x = { "one" => "one", "two" => "two", "three" => "three"}
y = x.some_function
y == { "one" => "one", "two" => "two"}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
编辑:应该提一下,在这个例子中,我希望它表现为白名单过滤器.也就是说,我知道我想要什么,而不是我不想要的.
Bri*_*rie 103
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" }
Run Code Online (Sandbox Code Playgroud)
这些都很好,我一直都在使用它们.
sri*_*ris 54
也许这就是你想要的.
wanted_keys = %w[one two]
x = { "one" => "one", "two" => "two", "three" => "three"}
x.select { |key,_| wanted_keys.include? key }
Run Code Online (Sandbox Code Playgroud)
包含在例如Array和Hash中的Enumerable mixin提供了很多有用的方法,比如select/reject/each/etc.我建议你看一下ri Enumerable的文档.
sco*_*ttd 49
你可以使用内置的Hash函数拒绝.
x = { "one" => "one", "two" => "two", "three" => "three"}
y = x.reject {|key,value| key == "three" }
y == { "one" => "one", "two" => "two"}
Run Code Online (Sandbox Code Playgroud)
您可以将任何您想要的逻辑放入拒绝中,如果该块返回true,它将跳过新哈希中的该键值.
改进一点@scottd答案,如果您使用rails并且列出了您需要的列表,则可以将列表作为参数从slice中展开.例如
hash = { "one" => "one", "two" => "two", "three" => "three"}
keys_whitelist = %W(one two)
hash.slice(*keys_whitelist)
Run Code Online (Sandbox Code Playgroud)
如果没有rails,对于任何ruby版本,您可以执行以下操作:
hash = { "one" => "one", "two" => "two", "three" => "three"}
keys_whitelist = %W(one two)
Hash[hash.find_all{|k,v| keys_whitelist.include?(k)}]
Run Code Online (Sandbox Code Playgroud)
结合每个人的答案,我提出了这个解决方案:
wanted_keys = %w[one two]
x = { "one" => "one", "two" => "two", "three" => "three"}
x.reject { |key,_| !wanted_keys.include? key }
=>{ "one" => "one", "two" => "two"}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
编辑:
以上工作在1.8.7+
以下适用于1.9+:
x.select {| key,_ | wanted_keys.include?键}
归档时间: |
|
查看次数: |
44000 次 |
最近记录: |