0
0
Rubyprogramming~5 mins

Open classes (reopening classes) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean to 'reopen' a class in Ruby?
Reopening a class means you can add new methods or change existing ones to a class even after it has been defined. Ruby lets you open any class again and modify it.
Click to reveal answer
beginner
How do you reopen a class in Ruby?
You reopen a class by writing the class keyword with the same class name again. Inside this block, you can add or change methods.
Click to reveal answer
intermediate
Why are open classes useful in Ruby?
Open classes let you fix bugs, add features, or change behavior of existing classes without changing the original source code. This is helpful for customizing libraries or core classes.
Click to reveal answer
intermediate
What is a risk of using open classes carelessly?
Changing core or library classes can cause unexpected bugs or conflicts if different parts of code expect different behaviors. It can make debugging harder.
Click to reveal answer
beginner
Example: How to add a method 'greet' to Ruby's String class using open classes?
class String
  def greet
    "Hello, #{self}!"
  end
end

"World".greet # => "Hello, World!"
Click to reveal answer
What happens when you reopen a class in Ruby?
AYou can add or change methods of that class.
BYou create a new class with the same name.
CYou delete the original class.
DYou convert the class to a module.
Which keyword is used to reopen a class in Ruby?
Adef
Bclass
Cmodule
Dopen
What is a potential problem when reopening core Ruby classes?
AIt deletes all existing methods.
BIt can make code run slower.
CIt can cause syntax errors.
DIt can cause unexpected bugs or conflicts.
Can you reopen a class multiple times in Ruby?
AOnly if the class is a module.
BNo, only once.
CYes, as many times as you want.
DOnly if the class is user-defined.
What will this code output? class String def shout upcase + "!" end end "hello".shout
A"HELLO!"
B"hello!"
CError: method shout not found
D"hello"
Explain what 'open classes' means in Ruby and give a simple example.
Think about how you can add methods to existing classes.
You got /3 concepts.
    What are the benefits and risks of using open classes in Ruby?
    Consider why you might want to change a class after it's defined and what could go wrong.
    You got /2 concepts.