Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 deleted key?

In Ruby (or Rails), we can do

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

and now new_params is a hash with an added key :order.

But is there a line there can return the hash with a deleted key? The line

new_params = params.delete(:order)

won't work because the delete method returns the value and that's it. Do we have to do it in 3 steps?

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

Is there a better way? Because I want to do a

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 clumsy. Is there a better way to do it?

(note: because the default order is 'desc', so when there is no order param, that means it is the default and is desc, then toggle it to add order=asc, but otherwise, just remove the param order so that it is back to the default order of desc)

like image 458
nonopolarity Avatar asked Apr 19 '11 12:04

nonopolarity


People also ask

How do you merge hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.

How do you make Hash Hash in Ruby?

Just like arrays, hashes can be created with hash literals. Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }.


2 Answers

ActiveSupport adds a Hash#except method:

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

A more complicated example:

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

This will update keys that are present in h1 with the ones in h2, add the new ones from h2 and remove the ones that are in h1 but not in h2.

like image 122
Michael Kohl Avatar answered Sep 22 '22 06:09

Michael Kohl


use reject:

{:hello=> 'aaa'}.reject {| key, value | key == :hello} #=> {}
like image 43
Vlad Khomich Avatar answered Sep 22 '22 06:09

Vlad Khomich