0
0
Rubyprogramming~20 mins

Instance_variable_get and set in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Instance Variable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
Anil
BError: undefined method `instance_variable_get' for Person
CAlice
D@name
Attempts:
2 left
💡 Hint
instance_variable_get reads the value of an instance variable by its name symbol.
Predict Output
intermediate
2: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)
A100
B0
Cnil
DError: undefined method `instance_variable_set' for Car
Attempts:
2 left
💡 Hint
instance_variable_set changes the value of an instance variable.
Predict Output
advanced
2: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")
ANo error, returns nil
BNameError
CArgumentError
DTypeError
Attempts:
2 left
💡 Hint
instance_variable_get expects a symbol or string starting with @.
Predict Output
advanced
2: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)
Aage
B30
Cnil
DError: undefined method `set_var' for User
Attempts:
2 left
💡 Hint
instance_variable_set and get can use string names with '@' prefix.
🧠 Conceptual
expert
2: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)
A4
B2
C3
D5
Attempts:
2 left
💡 Hint
instance_variable_set adds new instance variables if they don't exist.