0
0
Rubyprogramming~5 mins

Self keyword behavior in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the self keyword represent inside an instance method in Ruby?

Inside an instance method, self refers to the current object (instance) on which the method is called.

Click to reveal answer
beginner
How does <code>self</code> behave inside a class method in Ruby?
<p>Inside a class method, <code>self</code> refers to the class itself, not an instance.</p>
Click to reveal answer
intermediate
What is the value of <code>self</code> at the top level of a Ruby program (outside any class or method)?

At the top level, self refers to the main object, which is an instance of Object.

Click to reveal answer
beginner
Can self be reassigned to another object inside a method?

No, self is a special keyword and cannot be reassigned to a different object inside a method.

Click to reveal answer
intermediate
How does self help when defining setter methods in Ruby?

Using self.attribute = value inside a method calls the setter method instead of creating a local variable.

Click to reveal answer
Inside an instance method, what does self refer to?
AThe class itself
BThe current object (instance)
CThe main object
DA local variable
What does self refer to inside a class method?
AThe current instance
BThe main object
CA global variable
DThe class itself
At the top level of a Ruby program, self is:
AThe main object
BAn instance of the current class
CNil
DThe class object
Why do we use self.attribute = value inside a method?
ATo create a local variable
BTo call a class method
CTo call the setter method
DTo reassign <code>self</code>
Can you assign a new object to self inside a method?
ANo, <code>self</code> is special and cannot be reassigned
BOnly in class methods
COnly at the top level
DYes, anytime
Explain how the self keyword behaves differently inside instance methods, class methods, and at the top level in Ruby.
Think about what object is 'current' in each context.
You got /3 concepts.
    Describe why using self.attribute = value inside a method is important compared to just writing attribute = value.
    Consider how Ruby decides between local variables and method calls.
    You got /3 concepts.