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

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

    There are many ways to remove a key from a hash and get the remaining hash in Ruby.

    1. .slice => It will return selected keys and not delete them from the original hash. Use slice! if you want to remove the keys permanently else use simple slice.

      2.2.2 :074 > hash = {"one"=>1, "two"=>2, "three"=>3}
       => {"one"=>1, "two"=>2, "three"=>3} 
      2.2.2 :075 > hash.slice("one","two")
       => {"one"=>1, "two"=>2} 
      2.2.2 :076 > hash
       => {"one"=>1, "two"=>2, "three"=>3} 
      
    2. .delete => It will delete the selected keys from the original hash(it can accept only one key and not more than one).

      2.2.2 :094 > hash = {"one"=>1, "two"=>2, "three"=>3}
       => {"one"=>1, "two"=>2, "three"=>3} 
      2.2.2 :095 > hash.delete("one")
       => 1 
      2.2.2 :096 > hash
       => {"two"=>2, "three"=>3} 
      
    3. .except => It will return the remaining keys but not delete anything from the original hash. Use except! if you want to remove the keys permanently else use simple except.

      2.2.2 :097 > hash = {"one"=>1, "two"=>2, "three"=>3}
       => {"one"=>1, "two"=>2, "three"=>3} 
      2.2.2 :098 > hash.except("one","two")
       => {"three"=>3} 
      2.2.2 :099 > hash
       => {"one"=>1, "two"=>2, "three"=>3}         
      
    4. .delete_if => In case you need to remove a key based on a value. It will obviously remove the matching keys from the original hash.

      2.2.2 :115 > hash = {"one"=>1, "two"=>2, "three"=>3, "one_again"=>1}
       => {"one"=>1, "two"=>2, "three"=>3, "one_again"=>1} 
      2.2.2 :116 > value = 1
       => 1 
      2.2.2 :117 > hash.delete_if { |k,v| v == value }
       => {"two"=>2, "three"=>3} 
      2.2.2 :118 > hash
       => {"two"=>2, "three"=>3} 
      
    5. .compact => It is used to remove all nil values from the hash. Use compact! if you want to remove the nil values permanently else use simple compact.

      2.2.2 :119 > hash = {"one"=>1, "two"=>2, "three"=>3, "nothing"=>nil, "no_value"=>nil}
       => {"one"=>1, "two"=>2, "three"=>3, "nothing"=>nil, "no_value"=>nil} 
      2.2.2 :120 > hash.compact
       => {"one"=>1, "two"=>2, "three"=>3}
      

    Results based on Ruby 2.2.2.

提交回复
热议问题