Concept Flow - Instance_variable_get and set
Create Object
Set Instance Variable
Get Instance Variable
Use or Display Value
End
This flow shows creating an object, setting an instance variable, getting its value, and using it.
class Person def initialize(name) @name = name end end p = Person.new("Alice") p.instance_variable_get(:@name)
| Step | Action | Code/Method | Instance Variable State | Output |
|---|---|---|---|---|
| 1 | Create Person object | Person.new("Alice") | @name = "Alice" | Person object created |
| 2 | Initialize @name | initialize("Alice") | @name = "Alice" | None |
| 3 | Get @name value | instance_variable_get(:@name) | @name = "Alice" | "Alice" |
| 4 | Set @age value | instance_variable_set(:@age, 30) | @name = "Alice", @age = 30 | 30 |
| 5 | Get @age value | instance_variable_get(:@age) | @name = "Alice", @age = 30 | 30 |
| 6 | Get non-existing @height | instance_variable_get(:@height) | @name = "Alice", @age = 30 | nil |
| 7 | End | - | @name = "Alice", @age = 30 | Execution ends |
| Variable | Start | After Step 2 | After Step 4 | Final |
|---|---|---|---|---|
| @name | nil | "Alice" | "Alice" | "Alice" |
| @age | nil | nil | 30 | 30 |
| @height | nil | nil | nil | nil |
Instance_variable_get(:@var) returns the value of @var or nil if unset. Instance_variable_set(:@var, value) sets or creates @var with value. Use symbols or strings with @ prefix for variable names. Useful to access or change variables dynamically. Does not call getter/setter methods, works directly on variables.