从哈希循环中跳过密钥

Ash*_*kar 2 ruby hash ruby-on-rails

我正在对哈希值执行操作,可以说:

hash = { a: true, b: false, c: nil }
Run Code Online (Sandbox Code Playgroud)

我正在执行each循环,hash但我想跳过键bc。我不想从 中删除这些hash

我努力了:

hash = { a: true, b: false, c: nil}
hash.except(:c)
{ a: true, b: false, c: nil}
Run Code Online (Sandbox Code Playgroud)

但它不起作用。我在用ruby 2.4.2

Igo*_*dov 5

确实如预期hash.except(:c)返回{ a: true, b: false }。既然你正在使用Rails它应该可以工作。我想记下的唯一微妙的时刻是:

hash.except([:b, :c])
Run Code Online (Sandbox Code Playgroud)

行不通的。你需要使用

hash.except(:b, :c)
Run Code Online (Sandbox Code Playgroud)

反而。

对于一般解决方案,您需要使用 splat 运算符:

keys = [:b, :c]
hash.except(*keys)
Run Code Online (Sandbox Code Playgroud)