How do reject! and reject differ from delete_if for a Hash in Ruby? Can anyone explain the differences between them with simple code snippets?
How do reject! and reject differ from delete_if for a Hash in Ruby? Can
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since the other answers are referring to
Array#delete_ifand notHash#delete_if, which seems to be what you are asking, I thought I should clarify.As others have pointed out,
rejectandreject!differ in thatreject!version modifies the hash in-place, whilerejectcreates a new hash. Meanwhiledelete_ifis almost the same asreject!.In fact, for an
Array,reject!anddelete_ifare exactly the same.However, for a
Hash, they are slightly different.reject!returnsnilif no changes were made, or the hash if changes were made.delete_ifalways returns the hash.So if you wanted to check whether changes were made to the hash after deleting the elements, you could use
reject!and check the return value.