Concept Flow - Self keyword behavior
Start
Inside method
self refers to current object
Access or modify object's data
Method ends
The self keyword always points to the current object inside a method, letting you access or change that object's data.
class Person def initialize(name) @name = name end def show_self self end end p = Person.new("Alice") p.show_self
| Step | Action | self value | Instance variable @name | Output |
|---|---|---|---|---|
| 1 | Create Person object with name 'Alice' | Person object (not nil) | nil (before initialize) | None |
| 2 | Call initialize with 'Alice' | Person object | Set @name = 'Alice' | None |
| 3 | Call show_self method | Person object | @name = 'Alice' | Returns self (Person object) |
| 4 | Print show_self result | Person object | @name = 'Alice' | #<Person:0x... @name="Alice"> |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| self | nil | Person object (new) | Person object (in initialize) | Person object (in show_self) | Person object (returned) |
| @name | nil | nil | 'Alice' | 'Alice' | 'Alice' |
self keyword in Ruby: - Inside instance methods, self is the current object. - Use self to access or modify the object's data. - self is not the same as instance variables like @name. - Outside methods, self refers to the main context. - Helps clarify which object is being referenced.
self keyword represent inside an instance method in Ruby?self points toself refers to that specific object (instance) running the method.self in instance method = instance [OK]self in Ruby?self. inside the class.def self.my_method which is correct syntax. Others are invalid Ruby syntax.class Dog
def speak
self.class
end
end
fido = Dog.new
puts fido.speakself is inside speakspeak, self is the instance fido.self.classclass on the instance returns its class, which is Dog.self.class in instance method = class name [OK]class Cat
def self.meow
puts "Meow!"
end
def meow
puts "Meow from instance"
end
def self.instance_meow
meow
end
end
Cat.instance_meowself.instance_meowmeow without specifying an instance.meow without self. is an instance method, so it needs an object to call it on.meow inside a class method without an instance -> Option Bclass Calculator
def self.description
"I am a Calculator"
end
def initialize(value)
@value = value
end
def show_description
self.class.description
end
end
calc = Calculator.new(10)
puts calc.show_descriptionself.class.description inside instance methodshow_description, self is the instance calc. Calling class returns the class Calculator.descriptiondescription on the class returns the string "I am a Calculator".Pass the test and this pattern moves unknown