Bird
0
0

You have a class Person with unknown instance variables. How can you write a method update_var(name, value) that updates any instance variable dynamically using instance_variable_set?

hard📝 Application Q8 of 15
Ruby - Metaprogramming Fundamentals
You have a class Person with unknown instance variables. How can you write a method update_var(name, value) that updates any instance variable dynamically using instance_variable_set?
Adef update_var(name, value) instance_variable_set("@" + name.to_s, value) end
Bdef update_var(name, value) instance_variable_set(name.to_sym, value) end
Cdef update_var(name, value) instance_variable_set(:name, value) end
Ddef update_var(name, value) instance_variable_set(name, value) end
Step-by-Step Solution
Solution:
  1. Step 1: Understand instance_variable_set argument format

    The method requires the instance variable name with '@' prefix as symbol or string.
  2. Step 2: Build variable name dynamically

    Concatenate '@' with the string version of name, then pass as string or symbol. def update_var(name, value) instance_variable_set("@" + name.to_s, value) end does this correctly.
  3. Step 3: Check other options

    def update_var(name, value) instance_variable_set(name, value) end passes name directly without '@'. def update_var(name, value) instance_variable_set(:name, value) end uses literal :name symbol, not dynamic. def update_var(name, value) instance_variable_set(name.to_sym, value) end converts name to symbol but misses '@'.
  4. Final Answer:

    def update_var(name, value) instance_variable_set("@" + name.to_s, value) end -> Option A
  5. Quick Check:

    Prefix '@' to variable name string before setting [OK]
Quick Trick: Add '@' prefix to variable name string before setting [OK]
Common Mistakes:
  • Passing variable name without '@'
  • Using fixed symbol instead of dynamic name
  • Converting name to symbol without '@'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes