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

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

问题描述

  {: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有一个除/除!以外的其他内容。方法,该方法返回散列,并删除这些键。如果你已经使用Rails,那么创建你自己的版本是没有意义的。

  class Hash 
#返回一个散列,其中包含除给定键以外的所有内容。
#hash = {a:true,b:false,c:nil}
#hash.except(:c)#=> {a:true,b:false}
#hash#=> {a:true,b:false,c:nil}

#这对于一组参数限制一些已知切换的参数非常有用:
#@ person.update( (*键)
dup.except!(*键)
结束

#取代散列没有给定的键。
#hash = {a:true,b:false,c:nil}
#hash.except!(:c)#=> {a:true,b:false}
#hash#=> {a:true,b:false}
def除了!(*键)
keys.each {| key | delete(key)}
self
end
end


To add a new pair to Hash I do:

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

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

This works:

{: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 })

in one line.

解决方案

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天全站免登陆