Challenge - 5 Problems
Instance Variable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using instance_variable_get?
Consider the following Ruby class and code. What will be printed when this code runs?
Ruby
class Person def initialize(name) @name = name end end p = Person.new("Alice") puts p.instance_variable_get(:@name)
Attempts:
2 left
💡 Hint
instance_variable_get reads the value of an instance variable by its name symbol.
✗ Incorrect
The instance_variable_get method returns the value of the instance variable named by the symbol. Here, @name holds "Alice", so it prints Alice.
❓ Predict Output
intermediate2:00remaining
What does this code print after using instance_variable_set?
Look at this Ruby code. What will be the output?
Ruby
class Car def initialize @speed = 0 end end car = Car.new car.instance_variable_set(:@speed, 100) puts car.instance_variable_get(:@speed)
Attempts:
2 left
💡 Hint
instance_variable_set changes the value of an instance variable.
✗ Incorrect
The instance_variable_set method sets the value of @speed to 100. Then instance_variable_get returns 100, which is printed.
❓ Predict Output
advanced2:00remaining
What error does this code raise?
What error will this Ruby code produce when run?
Ruby
class Box def initialize @content = "secret" end end box = Box.new box.instance_variable_get("content")
Attempts:
2 left
💡 Hint
instance_variable_get expects a symbol or string starting with @.
✗ Incorrect
instance_variable_get requires the variable name to start with '@'. Passing "content" without '@' causes a TypeError.
❓ Predict Output
advanced2:00remaining
What is the output of this code using instance_variable_set dynamically?
What will this Ruby code print?
Ruby
class User def initialize @data = {} end def set_var(name, value) instance_variable_set("@" + name.to_s, value) end def get_var(name) instance_variable_get("@" + name.to_s) end end user = User.new user.set_var(:age, 30) puts user.get_var(:age)
Attempts:
2 left
💡 Hint
instance_variable_set and get can use string names with '@' prefix.
✗ Incorrect
The set_var method sets @age to 30. The get_var method retrieves @age, printing 30.
🧠 Conceptual
expert2:00remaining
How many instance variables does this object have after running the code?
After running this Ruby code, how many instance variables does the object 'obj' have?
Ruby
class Sample def initialize @a = 1 @b = 2 end end obj = Sample.new obj.instance_variable_set(:@c, 3) obj.instance_variable_set(:@d, 4) obj.instance_variable_get(:@a) obj.instance_variable_get(:@b)
Attempts:
2 left
💡 Hint
instance_variable_set adds new instance variables if they don't exist.
✗ Incorrect
Initially, obj has @a and @b. Then @c and @d are added by instance_variable_set. So total 4 instance variables.