0
0
Rubyprogramming~20 mins

Bang methods (ending with !) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Bang Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using a bang method?
Consider the following Ruby code snippet. What will be printed?
Ruby
arr = [1, 2, 3]
arr.reverse!
puts arr.inspect
Anil
B[1, 2, 3]
CError: undefined method 'reverse!'
D[3, 2, 1]
Attempts:
2 left
💡 Hint
Bang methods usually modify the object itself.
Predict Output
intermediate
2:00remaining
What does this string bang method return?
What will be the output of this Ruby code?
Ruby
str = "hello"
result = str.upcase!
puts result
puts str
A
nil
hello
B
HELLO
hello
C
HELLO
HELLO
DError: undefined method 'upcase!'
Attempts:
2 left
💡 Hint
upcase! changes the string itself and returns the modified string.
Predict Output
advanced
2:00remaining
What is the output when bang method does not change the object?
Look at this Ruby code. What will be printed?
Ruby
arr = [1, 2, 3]
result = arr.sort!
puts result.inspect
puts arr.inspect
A
nil
[1, 2, 3]
B
[1, 2, 3]
[1, 2, 3]
C
[3, 2, 1]
[3, 2, 1]
DError: undefined method 'sort!'
Attempts:
2 left
💡 Hint
Bang methods return nil if no changes were made.
Predict Output
advanced
2:00remaining
What error does this code raise?
What error will this Ruby code produce?
Ruby
num = 10
num.negate!
ANoMethodError: undefined method 'negate!' for 10:Integer
BSyntaxError: unexpected '!'
CTypeError: can't convert Integer to String
DRuntimeError: method negate! failed
Attempts:
2 left
💡 Hint
Check if Integer has a negate! method.
🧠 Conceptual
expert
2:00remaining
Why do Ruby bang methods sometimes return nil?
In Ruby, some bang methods return nil instead of the modified object. Why does this happen?
ABecause the method always returns nil by design
BBecause the method did not make any changes to the object
CBecause the object is frozen and cannot be changed
DBecause the method encountered an error during execution
Attempts:
2 left
💡 Hint
Think about what happens if the object is already in the desired state.