0
0
Rubyprogramming~5 mins

Class methods with self prefix in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Adef self.method_name
Bdef method_name
Cdef @method_name
Ddef #method_name
How do you call a class method named info in class Car?
Ainfo.Car
BCar.info
Ccar.info
DCar#info
Which of these is true about class methods?
AThey are only used inside instance methods.
BThey can access instance variables directly.
CThey are private by default.
DThey can be called without creating an object.
What will this code print?<br>
class Cat
  def self.sound
    puts 'Meow'
  end
end
Cat.sound
AError
Bsound
CMeow
DNothing
Can a class method access instance variables like @name?
ANo, because instance variables belong to objects.
BYes, always.
COnly if the class method is called on an instance.
DOnly if the instance variable is global.
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.