1

I need to check if the given both keys is present in hash. Checking is not the problem here but one of the keys may not be present and can return false. I need to delete only the keys that are present.

if model_changes.has_key?(name)
   model_changes.delete(name)
end  

if model_changes.has_key?(id)
   model_changes.delete(id)
end

Instead of writing in two separate conditions is it possible to combine and delete the present key

3
  • Why do you have to check if the keys are present? Commented Oct 22, 2019 at 6:43
  • what if a key is not present and delete action on that particular key is called Commented Oct 22, 2019 at 6:50
  • @Hermaraj : From the Ruby docs for Hash#delete : Deletes and returns a key-value pair from hsh whose key is equal to key. If the key is not found, returns the default value. hence, I would simply drop the test. Commented Oct 22, 2019 at 7:24

1 Answer 1

3

You can go following way,

hash = { foo: :foo, bar: :bar, meh: :meh }
output = hash.except(:meh, :bar)
# => {:foo=>:foo}
Sign up to request clarification or add additional context in comments.

1 Comment

Or except! to modify the hash in-place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.