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.
instance_variable_get do?instance_variable_get is used to access the value of an instance variable by passing its name as a symbol or string.@name to "Alice" using instance_variable_set?instance_variable_set must be the instance variable name as a symbol or string, including the '@' prefix.:@name symbol correctly.class Person
def initialize(name)
@name = name
end
end
p = Person.new("Bob")
puts p.instance_variable_get(:@name)@name variable is set to "Bob" in the constructor.instance_variable_get(:@name) returns the value "Bob" stored in @name.class Car
def initialize
@speed = 0
end
def set_speed(value)
instance_variable_set(:speed, value)
end
end
car = Car.new
car.set_speed(50)
puts car.instance_variable_get(:@speed)instance_variable_set must include '@' prefix to identify the instance variable.:speed is missing '@', so Ruby will not find the variable and will create a new one without '@', causing unexpected behavior.Box with private instance variable @content, how can you change its value to "Books" from outside the class using instance_variable_set?instance_variable_set with the symbol including '@' allows changing the private variable from outside.:@content. box.instance_variable_set(:conten, "Books") misses '@', box.@content = "Books" is invalid syntax, box.set_content("Books") assumes a setter method which may not exist.Pass the test and this pattern moves unknown