0
0
Rubyprogramming~20 mins

Open classes (reopening classes) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Open Classes 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 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
AHELLO!
Bhello!
CError: undefined method 'shout' for String
Dhello
Attempts:
2 left
💡 Hint
Reopening a class allows you to add new methods to existing classes.
Predict Output
intermediate
2: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)
AError: wrong number of arguments for push
B"Cannot add elements"
C[1, 2, 3]
D3
Attempts:
2 left
💡 Hint
Redefining a method replaces the original behavior.
🔧 Debug
advanced
2: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
AError because Integer is a built-in class and cannot be reopened
BError because method double is defined twice without aliasing
CNo error; outputs 10 then 7
DError because puts is called outside any method
Attempts:
2 left
💡 Hint
Ruby allows reopening built-in classes and redefining methods.
🧠 Conceptual
advanced
2: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?
AIt causes Ruby to crash immediately
BIt makes the program run slower because classes are duplicated
CIt prevents you from using built-in methods anymore
DIt can cause conflicts if multiple libraries redefine the same method differently
Attempts:
2 left
💡 Hint
Think about what happens if two pieces of code change the same method.
Predict Output
expert
2: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
AReversed: cba
Babc
CError: super called outside method
DReversed: abc
Attempts:
2 left
💡 Hint
super calls the original method from the class before reopening.