如何从哈希中删除一个键并在 Ruby/Rails 中获取剩余的哈希? [英] How to remove a key from Hash and get the remaining hash in Ruby/Rails?

查看:23
本文介绍了如何从哈希中删除一个键并在 Ruby/Rails 中获取剩余的哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要向 Hash 我添加一个新的对:

To add a new pair to Hash I do:

{:a => 1, :b => 2}.merge!({:c => 3})   #=> {:a => 1, :b => 2, :c => 3}

有没有类似的方法从 Hash 中删除一个键?

Is there a similar way to delete a key from Hash ?

这行得通:

{:a => 1, :b => 2}.reject! { |k| k == :a }   #=> {:b => 2}

但我希望有类似的东西:

but I would expect to have something like:

{:a => 1, :b => 2}.delete!(:a)   #=> {:b => 2}

返回值是剩余的哈希值很重要,所以我可以这样做:

It is important that the returning value will be the remaining hash, so I could do things like:

foo(my_hash.reject! { |k| k == my_key })

一行.

推荐答案

Rails 有一个 except/除了!方法 返回删除了这些键的哈希值.如果您已经在使用 Rails,那么创建自己的版本是没有意义的.

Rails has an except/except! method that returns the hash with those keys removed. If you're already using Rails, there's no sense in creating your own version of this.

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 中获取剩余的哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆