Challenge - 5 Problems
Ruby Open Classes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of reopening a class and adding a method?
Consider the following Ruby code that reopens the String class to add a new method. What will be printed when the code runs?
Ruby
class String def shout self.upcase + "!" end end puts "hello".shout
Attempts:
2 left
💡 Hint
Reopening a class allows you to add new methods to existing classes.
✗ Incorrect
The String class is reopened and a new method shout is added. Calling shout on "hello" returns the uppercase version plus an exclamation mark.
❓ Predict Output
intermediate2:00remaining
What happens when you redefine an existing method in a reopened class?
Look at this Ruby code where the Array class is reopened and the push method is redefined. What will be the output?
Ruby
class Array def push(element) "Cannot add elements" end end arr = [1, 2] puts arr.push(3)
Attempts:
2 left
💡 Hint
Redefining a method replaces the original behavior.
✗ Incorrect
The push method is redefined to always return the string "Cannot add elements" instead of adding to the array.
🔧 Debug
advanced2:00remaining
Why does this reopened class code raise an error?
This code reopens the Integer class to add a method, but it raises an error. What is the cause?
Ruby
class Integer def double self * 2 end end puts 5.double class Integer def double self + 2 end end puts 5.double
Attempts:
2 left
💡 Hint
Ruby allows reopening built-in classes and redefining methods.
✗ Incorrect
Ruby allows reopening Integer and redefining methods. The first puts prints 10 (5*2), the second prints 7 (5+2). No error occurs.
🧠 Conceptual
advanced2:00remaining
What is a risk of reopening core Ruby classes?
Reopening core Ruby classes like String or Array can be powerful but risky. Which of these is the main risk?
Attempts:
2 left
💡 Hint
Think about what happens if two pieces of code change the same method.
✗ Incorrect
Reopening core classes and redefining methods can cause conflicts and unexpected behavior if different code changes the same method in incompatible ways.
❓ Predict Output
expert2:00remaining
What is the output after reopening a class and using super?
Examine this Ruby code where the String class is reopened and the reverse method is redefined using super. What will be printed?
Ruby
class String def reverse "Reversed: " + super end end puts "abc".reverse
Attempts:
2 left
💡 Hint
super calls the original method from the class before reopening.
✗ Incorrect
The new reverse method calls super to get the original reversed string, then adds "Reversed: " before it.