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

前端 未结 15 1834
梦如初夏
梦如初夏 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条回答
  •  Happy的楠姐
    2020-12-04 05:04

    If you want to use pure Ruby (no Rails), don't want to create extension methods (maybe you need this only in one or two places and don't want to pollute namespace with tons of methods) and don't want to edit hash in place (i.e., you're fan of functional programming like me), you can 'select':

    >> x = {:a => 1, :b => 2, :c => 3}
    => {:a=>1, :b=>2, :c=>3}
    >> x.select{|x| x != :a}
    => {:b=>2, :c=>3}
    >> x.select{|x| ![:a, :b].include?(x)}
    => {:c=>3}
    >> x
    => {:a=>1, :b=>2, :c=>3}
    

提交回复
热议问题