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
Serve Current Directory from Command Line
Getting "Warning! Path Is Not Properly Set Up" When Doing Rvm Use 2.0.0 --Default
How to Create a Private Class Method
How to Get the Name of a Ruby Class
How to Use CSS with a Ruby on Rails Application
How to Match Something With Regex That Is Not Between Two Special Characters
Json Encoding Wrongly Escaped (Rails 3, Ruby 1.9.2)
Storing Objects in a Session in Rails
Launching Background Process in Capistrano Task
How to Make an Http Get With Modified Headers
Rails Installation Failed on Ubuntu With "Cannot Load Such File - Mkmf"
Ruby: "Gem Install Bundler" Not Installing Bundler
How to Compile and Statically Link Ruby Libs for Docker
Invalid Active Developer Path on MAC Os X After Installing Ruby
Using God to Monitor Unicorn - Start Exited with Non-Zero Code = 1
Getting Fields_For and Accepts_Nested_Attributes_For to Work With a Belongs_To Relationship
In Ruby, Is There an Array Method That Combines 'Select' and 'Map'