Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 similar way to delete a key from Hash ?

This works:

{:a => 1, :b => 2}.reject! { |k| k == :a }   #=> {:b => 2} 

but I would expect to have something like:

{:a => 1, :b => 2}.delete!(:a)   #=> {:b => 2} 

It is important that the returning value will be the remaining hash, so I could do things like:

foo(my_hash.reject! { |k| k == my_key }) 

in one line.

like image 311
Misha Moroshko Avatar asked Jun 03 '11 13:06

Misha Moroshko


People also ask

How do I get the hash value in Ruby?

hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.

How do you replace a hash in Ruby?

The contents of a certain hash can be replaced in Ruby by using the replace() method. It replaces the entire contents of a hash with the contents of another hash.

How do you check if a hash has a key Ruby?

Overview. We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.


1 Answers

Rails has an except/except! method that returns the hash with those keys removed. If you're already using Rails, there's no sense in creating your own version of this.

class Hash   # Returns a hash that includes everything but the given keys.   #   hash = { a: true, b: false, c: nil}   #   hash.except(:c) # => { a: true, b: false}   #   hash # => { a: true, b: false, c: nil}   #   # This is useful for limiting a set of parameters to everything but a few known toggles:   #   @person.update(params[:person].except(:admin))   def except(*keys)     dup.except!(*keys)   end    # Replaces the hash without the given keys.   #   hash = { a: true, b: false, c: nil}   #   hash.except!(:c) # => { a: true, b: false}   #   hash # => { a: true, b: false }   def except!(*keys)     keys.each { |key| delete(key) }     self   end end 
like image 123
Peter Brown Avatar answered Sep 22 '22 09:09

Peter Brown