How to remove a key from Hash and get the remaining hash in Ruby/Rails?

前端 未结 15 1825
梦如初夏
梦如初夏 2020-12-04 04:26

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 simi

相关标签:
15条回答
  • 2020-12-04 05:21

    You can use except! from the facets gem:

    >> require 'facets' # or require 'facets/hash/except'
    => true
    >> {:a => 1, :b => 2}.except(:a)
    => {:b=>2}
    

    The original hash does not change.

    EDIT: as Russel says, facets has some hidden issues and is not completely API-compatible with ActiveSupport. On the other side ActiveSupport is not as complete as facets. In the end, I'd use AS and let the edge cases in your code.

    0 讨论(0)
  • 2020-12-04 05:23

    Why not just use:

    hash.delete(key)
    
    0 讨论(0)
  • 2020-12-04 05:24

    in pure Ruby:

    {:a => 1, :b => 2}.tap{|x| x.delete(:a)}   # => {:b=>2}
    
    0 讨论(0)
提交回复
热议问题