添加一对新的哈希,我做:
{: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 })
在一行里。
如果你正在使用Ruby 2,你可以使用改进,而不是猴子补丁或不必要地包括大型库:
module HashExtensions
refine Hash do
def except!(*candidates)
candidates.each { |candidate| delete(candidate) }
self
end
def except(*candidates)
dup.remove!(candidates)
end
end
end
您可以在不影响程序其他部分的情况下使用此特性,也不必包含大型外部库。
class FabulousCode
using HashExtensions
def incredible_stuff
delightful_hash.except(:not_fabulous_key)
end
end
#in lib/core_extensions.rb
class Hash
#pass single or array of keys, which will be removed, returning the remaining hash
def remove!(*keys)
keys.each{|key| self.delete(key) }
self
end
#non-destructive version
def remove(*keys)
self.dup.remove!(*keys)
end
end
#in config/initializers/app_environment.rb (or anywhere in config/initializers)
require 'core_extensions'
我已经设置好了,所以.remove返回一个删除键的散列副本,而remove!修改哈希本身。这与ruby的约定是一致的。从控制台
>> hash = {:a => 1, :b => 2}
=> {:b=>2, :a=>1}
>> hash.remove(:a)
=> {:b=>2}
>> hash
=> {:b=>2, :a=>1}
>> hash.remove!(:a)
=> {:b=>2}
>> hash
=> {:b=>2}
>> hash.remove!(:a, :b)
=> {}
Rails有一个except/except!方法,该方法返回删除了这些键后的散列。如果您已经在使用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(没有Rails),不想创建扩展方法(也许你只需要在一两个地方使用扩展方法,不想用大量的方法污染命名空间),不想在适当的地方编辑散列(也就是说,你像我一样是函数式编程的粉丝),你可以“选择”:
>> x = {:a => 1, :b => 2, :c => 3}
=> {:a=>1, :b=>2, :c=>3}
>> x.select{|x| x != :a}
=> {:b=>2, :c=>3}
>> x.select{|x| ![:a, :b].include?(x)}
=> {:c=>3}
>> x
=> {:a=>1, :b=>2, :c=>3}