How to Remove a Key from Hash and Get the Remaining Hash in Ruby/Rails

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

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

Deleting a key-value pair from hash (RUBY)

Hash#delete returns the value of provided key, movies.delete("Divergent".to_sym) returns 4.7, and you reassign it to movies, now movies is 4.7.

So you could just delete and don't reassign:

movies.delete("Divergent".to_sym)
print movies # => {:StarWars=>4.8}

Remove Hash from array based on key in Ruby

Elements of the array are hashes, so you need to treat them as hashes:

@array.delete_if{|h| h[:total_duration] == 0}
# => [{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]
@array
#=> [{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]

remove specific keys (and values) from a ruby hash

Hash#except, Hash#except! do not accepts an array of keys, but keys as arbitrary parameters. You need to use * operator to convert the array into method arguments:

result_hash.except(*suppression_list)

removing a value from hash if key matches rails

More generic solution: for the hash given as an input (I assume it’s params, so let’s call it params) and the list of fields to be removed when empty:

TO_REMOVE_EMPTY = %w|password|
params.delete_if { |k, v| TO_REMOVE_EMPTY.include?(k) && v.empty? }

Is there an elegant way to remove a specific key from a hash and it's sub-hashes in Ruby

I don't think there is a built in method for this so a simple recursive method along the following lines is one solution:

def recursive_delete(hash, to_remove)
hash.delete(to_remove)
hash.each_value do |value|
recursive_delete(value, to_remove) if value.is_a? Hash
end
end

With your example data:

h = { :action => "index", :controller => "home", :secret => "I love Jeff Atwood",
:user => {:name => "Steve", :secret => "I steal Joel's pants"}}

recursive_delete(h, :secret)

puts h.inspect

Gives:

{:controller=>"home", :user=>{:name=>"Steve"}, :action=>"index"}

Note that this solution works in place i.e. it is modifying the original Hash, not returning a new Hash with the requested key excluded.



Related Topics



Leave a reply



Submit