Created
October 12, 2022 10:05
-
-
Save thiagofm/97822874c1a51a1c19734f063f6fb97e to your computer and use it in GitHub Desktop.
bang methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Bang method behavior: upcase! | |
email = "test@test.com" | |
# Upcasing a string, but not changing the variable email's value | |
email.upcase | |
# => "TEST@TEST.COM" | |
# => "test@test.com" | |
# Using bang to upcase a string | |
email.upcase! | |
# => "TEST@TEST.COM" | |
# => "TEST@TEST.COM" | |
# ⚠️ Now look at this weird behavior with !upcase: | |
# As email is already upcased... | |
email.upcase! | |
# => nil | |
# It returns nil... if it didn't need to change it. 😵💫 | |
# On Ruby on Rails, we have the find_by and find_by! methods | |
# find_by! raises an exception when it can't find a record. | |
# Wrapping up: bang methods are about all about warning the developer | |
# that the new method behavior differs from its other version. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment