Recall & Review
beginner
What does
instance_variable_get do in Ruby?It reads the value of an instance variable from an object, even if the variable is private or not accessible by normal methods.
Click to reveal answer
beginner
How do you use
instance_variable_set in Ruby?You call it on an object with the variable name (as a symbol or string starting with '@') and the new value to assign to that instance variable.
Click to reveal answer
intermediate
Why might you use
instance_variable_get and instance_variable_set instead of normal getters and setters?They let you access or change instance variables directly, even if no getter or setter methods exist or if the variables are private.Click to reveal answer
beginner
What is the correct syntax to get the value of an instance variable named
@name from an object obj?obj.instance_variable_get(:@name)Click to reveal answer
beginner
What happens if you try to get an instance variable that does not exist using
instance_variable_get?It returns
nil because the variable is not set on the object.Click to reveal answer
Which symbol correctly represents an instance variable named 'age' for use with
instance_variable_get?✗ Incorrect
Instance variable names must start with '@' and be passed as symbols or strings, so :@age is correct.
What will
obj.instance_variable_get(:@score) return if @score is not set on obj?✗ Incorrect
If the instance variable does not exist,
instance_variable_get returns nil.How do you set the instance variable
@level to 5 on an object player?✗ Incorrect
Use
instance_variable_set with the variable name as a symbol starting with '@' and the value.Why might using
instance_variable_get and instance_variable_set be discouraged in normal code?✗ Incorrect
Directly accessing instance variables bypasses encapsulation, which can lead to fragile code.
Which of these is a valid use of
instance_variable_get?✗ Incorrect
The variable name must start with '@' and be passed as a symbol or string; :@name is correct.
Explain how
instance_variable_get and instance_variable_set work in Ruby and when you might use them.Think about how you can read or change private data inside an object.
You got /4 concepts.
Describe the risks or downsides of using
instance_variable_get and instance_variable_set in your Ruby programs.Consider how direct access to internal data affects code design.
You got /4 concepts.