Skip to content

Instantly share code, notes, and snippets.

@thiagofm
Created October 12, 2022 10:05
Show Gist options
  • Save thiagofm/97822874c1a51a1c19734f063f6fb97e to your computer and use it in GitHub Desktop.
Save thiagofm/97822874c1a51a1c19734f063f6fb97e to your computer and use it in GitHub Desktop.
bang methods
# Bang method behavior: upcase!
email = "test@test.com"
# Upcasing a string, but not changing the variable email's value
email.upcase
# => "TEST@TEST.COM"
email
# => "test@test.com"
# Using bang to upcase a string
email.upcase!
# => "TEST@TEST.COM"
email
# => "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