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

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

    Multiple ways to delete Key in Hash. you can use any Method from below

    hash = {a: 1, b: 2, c: 3}
    hash.except!(:a) # Will remove *a* and return HASH
    hash # Output :- {b: 2, c: 3}
    
    hash = {a: 1, b: 2, c: 3}
    hash.delete(:a) # will remove *a* and return 1 if *a* not present than return nil
    

    So many ways is there, you can look on Ruby doc of Hash here.

    Thank you

提交回复
热议问题