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.