In Ruby or Rails, hash.merge ({: order => 'asc'}) can return a new hash with a new key. What can return a new hash with a remote key?

In Ruby (or Rails) we can do

new_params = params.merge({:order => 'asc'})

and is now new_paramsa hash with an added key :order.

But is there a line returning a hash with the remote key? Line

new_params = params.delete(:order)

will not work because the method deletereturns a value and its value. Should we do this in 3 steps?

tmp_params = params
tmp_params.delete(:order)
return tmp_params

Is there a better way? Because I want to do

new_params = (params[:order].blank? || params[:order] == 'desc') ? 
               params.merge({:order => 'asc') : 
               (foo = params; foo.delete(:order); foo)   # return foo

but the last line above is somewhat awkward. Is there a better way to do this?

( : - "desc", , order, , desc, order=asc, order, desc)

+5
3

ActiveSupport Hash#except:

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

:

h1 = { a:1, b: 2, c: 3 }
h2 = { b: 3, d: 5 }
h1.merge(h2).except(*h1.keys-h2.keys) #=> {:b=>3, :d=>5}

, h1, h2, h2 , h1, h2.

+10

:

{:hello=> 'aaa'}.reject {| key, value | key == :hello} #=> {}
+1

ActiveSupport, :

params.delete_if {|key, value| key == :order }
+1
source

All Articles