Complete the code to get the value of the instance variable @name.
class Person def initialize(name) @name = name end def get_name [1] end end person = Person.new("Alice") puts person.get_name
The method instance_variable_get(:@name) returns the value of the instance variable @name.
Complete the code to set the value of the instance variable @age to 30.
class Person def initialize(age) [1] end def get_age instance_variable_get(:@age) end end person = Person.new(30) puts person.get_age
The method instance_variable_set(:@age, age) sets the instance variable @age to the value of age.
Fix the error in the code to correctly set the instance variable @city to 'Paris'.
class Location def initialize(city) [1] end def get_city instance_variable_get(:@city) end end loc = Location.new("Paris") puts loc.get_city
The correct way to set the instance variable using instance_variable_set requires the variable name as a symbol with '@' and the value.
Fill both blanks to create a hash of instance variable names and their values for variables with names longer than 3 characters.
class Data def initialize @id = 1 @name = "Data" @val = 100 end def long_vars vars = instance_variables.select { |var| var.to_s.[1] 3 } { var => instance_variable_get(var) [2] var in vars } end end data = Data.new puts data.long_vars
The code selects instance variables with names longer than 3 characters using var.to_s.length > 3 and creates a hash using a for loop.
Fill all three blanks to set an instance variable dynamically, get its value, and print it.
class DynamicVar def set_var(name, value) [1] end def get_var(name) [2] end end obj = DynamicVar.new obj.set_var(:@color, "blue") puts [3]
The method set_var uses instance_variable_set(name, value) to set the variable. The method get_var uses instance_variable_get(name) to get it. Finally, printing obj.instance_variable_get(:@color) shows the value.