0
0
Rubyprogramming~5 mins

Bang methods (ending with !) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does a bang method (ending with !) indicate in Ruby?
A bang method usually means it performs a more "dangerous" or "destructive" action, often modifying the object it is called on instead of returning a new object.
Click to reveal answer
beginner
Example: What is the difference between upcase and upcase! methods on a string?
upcase returns a new string with all uppercase letters, leaving the original string unchanged. upcase! changes the original string itself to uppercase and returns nil if no changes were made.
Click to reveal answer
intermediate
Does every bang method modify the object it is called on?
Usually yes, but not always. Bang methods often modify the object, but the main idea is that they are "dangerous" or have side effects compared to their non-bang counterparts.
Click to reveal answer
beginner
What does gsub vs gsub! do on a string?
gsub returns a new string with replacements, leaving the original unchanged. gsub! modifies the original string in place and returns nil if no replacements were made.
Click to reveal answer
beginner
Why should you be careful when using bang methods?
Because they can change the original object, which might cause unexpected bugs if you rely on the original data elsewhere in your program.
Click to reveal answer
What does a bang method (ending with !) usually do in Ruby?
AModifies the object it is called on
BReturns a new object without changing the original
CAlways raises an error
DIs slower than non-bang methods
What will str.upcase! return if str is already uppercase?
Afalse
BThe uppercase string
CAn error
Dnil
Which method modifies the original string in place?
Aupcase
Bgsub
Cgsub!
Ddowncase
Are all bang methods guaranteed to modify the object?
AYes, always
BNo, but usually
CNo, never
DOnly if the object is a string
Why might you avoid using bang methods carelessly?
AThey can cause unexpected changes to data
BThey always raise exceptions
CThey don't work on arrays
DThey are slower
Explain what a bang method is in Ruby and how it differs from its non-bang counterpart.
Think about how the method changes the object it is called on.
You got /4 concepts.
    Give an example of a bang method on strings and describe what happens when you use it.
    Consider how the string changes after calling the method.
    You got /4 concepts.