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

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

    Hash#except (Ruby 3.0+)

    Starting from Ruby 3.0, Hash#except is a build-in method.

    As a result, there is no more need to depend on ActiveSupport or write monkey-patches in order to use it.

    h = { a: 1, b: 2, c: 3 }
    p h.except(:a) #=> {:b=>2, :c=>3}
    

    Sources:

    • Hash#except from official Ruby docs.
    • Link to the PR.
    • Ruby 3.0 adds Hash#except and ENV.except.

提交回复
热议问题