我想知道是否可以从哈希中收集许多属性。
当前使用 ruby 2.6.3
类似的东西
hash = { name: "Foo", email: "Bar", useless: nil }
other_hash = hash[:name, :email]
输出应该是另一个哈希,但没有无用的键/值
您可以使用Ruby内置的Hash#slice
:
hash = { name: "Foo", email: "Bar", useless: nil }
p hash.slice(:name, :email)
# {:name=>"Foo", :email=>"Bar"}
如果使用 Rails,您可以使用只接收要省略的键的Hash#except
:
p hash.except(:useless)
# {:name=>"Foo", :email=>"Bar"}
如果无用的键是这样,因为有nil
值,你也可以使用 Hash#compact:
h = { name: "Foo", email: "Bar", useless: nil }
h.compact #=> {:name=>"Foo", :email=>"Bar"}