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

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

    Instead of monkey patching or needlessly including large libraries, you can use refinements if you are using 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
    

    You can use this feature without affecting other parts of your program, or having to include large external libraries.

    class FabulousCode
      using HashExtensions
    
      def incredible_stuff
        delightful_hash.except(:not_fabulous_key)
      end
    end
    

提交回复
热议问题