The @name variable is set to "Bob" in the constructor.
Step 2: Use instance_variable_get to read value
Calling instance_variable_get(:@name) returns the value "Bob" stored in @name.
Final Answer:
Bob -> Option A
Quick Check:
instance_variable_get returns stored value [OK]
Hint: instance_variable_get returns actual stored value [OK]
Common Mistakes:
Expecting variable name instead of value
Confusing with nil if variable not set
Thinking it raises error if variable exists
4. Identify the issue in this Ruby code snippet:
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)
medium
A. The variable @speed is not initialized.
B. Cannot call instance_variable_set inside a method.
C. Missing '@' in instance_variable_set argument name.
D. instance_variable_get should use string, not symbol.
Solution
Step 1: Check instance_variable_set argument
The argument to instance_variable_set must include '@' prefix to identify the instance variable.
Step 2: Identify the error
Here, :speed is missing '@', so Ruby will not find the variable and will create a new one without '@', causing unexpected behavior.
Final Answer:
Missing '@' in instance_variable_set argument name. -> Option C
Quick Check:
Always include '@' in variable name for instance_variable_set [OK]
Hint: Always prefix variable name with '@' in set/get methods [OK]
Common Mistakes:
Omitting '@' in variable name
Thinking instance_variable_set can't be used in methods
Confusing symbol and string usage
5. Given a class Box with private instance variable @content, how can you change its value to "Books" from outside the class using instance_variable_set?
hard
A. box.instance_variable_set(:conten, "Books")
B. box.instance_variable_set(:@content, "Books")
C. box.@content = "Books"
D. box.set_content("Books")
Solution
Step 1: Understand private variable access
Private instance variables cannot be accessed or changed directly from outside the class using normal assignment.
Step 2: Use instance_variable_set with correct name
Using instance_variable_set with the symbol including '@' allows changing the private variable from outside.
Step 3: Check options
box.instance_variable_set(:@content, "Books") correctly uses :@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.
Final Answer:
box.instance_variable_set(:@content, "Books") -> Option B
Quick Check:
Use instance_variable_set with '@' to change private vars [OK]
Hint: Use '@' prefix symbol to set private variables externally [OK]
Common Mistakes:
Omitting '@' in variable name
Trying direct assignment to private variable
Assuming setter method exists
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.