How would I remove a specific value from a hash in Ruby

Viewed 39

Really new to Ruby and just trying to figure out how to remove one specific value from a hash and return a new hash.

So say if I had the hash

{"within" => ["FID6", "S5"],
"uri"=>"/repositories/2/raps/7",
"is_repository_default"=>false}

How would I go about removing the "FID6" value and returning a new hash without that value? I've tried to .delete("within") but that just broke my code.

2 Answers

You can use Hash#transform_values to iterate over each value from the hash, modify them when they're arrays and return a new hash:

data = { "within" => ["FID6", "S5"], "uri"=>"/repositories/2/raps/7", "is_repository_default"=>false }
data.transform_values { |value| value.is_a?(Array) ? value - ['FID6'] : value }
# {"within"=>["S5"], "uri"=>"/repositories/2/raps/7", "is_repository_default"=>false}

Or to map a new hash starting from what you have:

data.map { |key, value| [key, value.is_a?(Array) ? value - ['FID6'] : value] }.to_h # {"within"=>["S5"], "uri"=>"/repositories/2/raps/7", "is_repository_default"=>false}
data.to_h { |key, value| [key, value.is_a?(Array) ? value - ['FID6'] : value] }     # {"within"=>["S5"], "uri"=>"/repositories/2/raps/7", "is_repository_default"=>false}

Hash#to_h accepts a block since Ruby 2.6

You can duplicate the hash and assign a new array with the value removed:

hash = { "within" => ["FID6", "S5"], "uri" => "/repositories/2/raps/7", "is_repository_default" => false }

new_hash = hash.dup
new_hash['within'] -= ['FID6']

new_hash
#=> {"within"=>["S5"], "uri"=>"/repositories/2/raps/7", "is_repository_default"=>false}

hash
#=> {"within"=>["FID6", "S5"], "uri"=>"/repositories/2/raps/7", "is_repository_default"=>false}
Related