Bird
0
0

Which of the following correctly retrieves the value of the instance variable @age from an object person?

easy📝 Conceptual Q2 of 15
Ruby - Metaprogramming Fundamentals
Which of the following correctly retrieves the value of the instance variable @age from an object person?
Aperson.get_instance_variable(:age)
Bperson.instance_variable_set(:@age)
Cperson.instance_variable_get(:@age)
Dperson.@age
Step-by-Step Solution
Solution:
  1. Step 1: Identify method to get instance variable

    The method to retrieve an instance variable's value by name is instance_variable_get, which takes the variable name as a symbol or string.
  2. Step 2: Check syntax correctness

    person.instance_variable_get(:@age) uses person.instance_variable_get(:@age), which is correct. person.instance_variable_set(:@age) tries to set, not get. person.get_instance_variable(:age) uses a non-existent method. person.@age is invalid syntax.
  3. Final Answer:

    person.instance_variable_get(:@age) -> Option C
  4. Quick Check:

    instance_variable_get retrieves value [OK]
Quick Trick: Use instance_variable_get(:@var) to read instance variables [OK]
Common Mistakes:
  • Using instance_variable_set instead of get
  • Wrong method names like get_instance_variable
  • Trying to access with dot notation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes