2

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.

1
  • 2
    Just to clarify and add to your knowledge you are wanting to remove the first element of an Array that is inside a hash as denoted by the square [] brackets Commented Jun 24, 2020 at 4:18

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Or maybe use shift to remove the first element of the array?
I don't usually use shift as it mutates the receiver @jamesc :( (a matter of preference).
1

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} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.