Recall & Review
beginner
What does the
self prefix mean in a Ruby method definition inside a class?The <code>self</code> prefix means the method is a class method. It belongs to the class itself, not to instances of the class.Click to reveal answer
beginner
How do you call a class method defined with <code>self.method_name</code> in Ruby?You call it on the class directly, like <code>ClassName.method_name</code>, without creating an instance.Click to reveal answer
intermediate
Why use class methods instead of instance methods?Class methods are used for actions related to the class as a whole, like creating new instances or utility functions, while instance methods work on individual objects.Click to reveal answer
beginner
Example: What does this code do?<br><pre>class Dog
def self.bark
puts 'Woof!'
end
end</pre>Defines a class method <code>bark</code> on <code>Dog</code>. You can call <code>Dog.bark</code> to print 'Woof!'.Click to reveal answer
intermediate
Can class methods access instance variables directly? Why or why not?No, class methods cannot access instance variables directly because instance variables belong to individual objects, not the class itself.Click to reveal answer
How do you define a class method in Ruby?
✗ Incorrect
Class methods are defined with
def self.method_name inside the class.How do you call a class method named
info in class Car?✗ Incorrect
Class methods are called on the class itself, like
Car.info.Which of these is true about class methods?
✗ Incorrect
Class methods belong to the class and can be called without creating an instance.
What will this code print?<br>
class Cat
def self.sound
puts 'Meow'
end
end
Cat.sound✗ Incorrect
Calling
Cat.sound runs the class method and prints 'Meow'.Can a class method access instance variables like
@name?✗ Incorrect
Instance variables belong to individual objects, so class methods cannot access them directly.
Explain what a class method is in Ruby and how it differs from an instance method.
Think about who owns the method: the class or the object.
You got /4 concepts.
Describe a situation where you would use a class method instead of an instance method.
When the action relates to the whole class, not a single object.
You got /4 concepts.