要将新对添加到哈希,我会这样做:
{:a => 1, :b => 2}.merge!({:c => 3}) #=> {:a => 1, :b => 2, :c => 3}
有没有类似的方法从哈希中删除一个键?
这个有效:
{:a => 1, :b => 2}.reject! { |k| k == :a } #=> {:b => 2}
但我希望有类似的东西:
{:a => 1, :b => 2}.delete!(:a) #=> {:b => 2}
重要的是返回值将是剩余的哈希值,所以我可以这样做:
foo(my_hash.reject! { |k| k == my_key })
一行。
最佳答案
Rails has an except/except! method返回删除了这些键的散列。如果您已经在使用 Rails,那么创建您自己的版本是没有意义的。
class Hash
# Returns a hash that includes everything but the given keys.
# hash = { a: true, b: false, c: nil}
# hash.except(:c) # => { a: true, b: false}
# hash # => { a: true, b: false, c: nil}
#
# This is useful for limiting a set of parameters to everything but a few known toggles:
# @person.update(params[:person].except(:admin))
def except(*keys)
dup.except!(*keys)
end
# Replaces the hash without the given keys.
# hash = { a: true, b: false, c: nil}
# hash.except!(:c) # => { a: true, b: false}
# hash # => { a: true, b: false }
def except!(*keys)
keys.each { |key| delete(key) }
self
end
end
关于ruby-on-rails - 如何从哈希中删除一个键并在 Ruby/Rails 中获取剩余的哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6227600/