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

前端 未结 15 1860
梦如初夏
梦如初夏 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:13

    #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'
    

    I've set this up so that .remove returns a copy of the hash with the keys removed, while remove! modifies the hash itself. This is in keeping with ruby conventions. eg, from the console

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

提交回复
热议问题