Bird
0
0

How can you modify this class to add an instance method age_in_months that returns the age in months?

hard📝 Application Q9 of 15
Ruby - Classes and Objects

How can you modify this class to add an instance method age_in_months that returns the age in months?

class Person
  def initialize(age)
    @age = age
  end
end
Adef age_in_months; @age * 12; end
Bdef age_in_months; age * 12; end
Cdef age_in_months; @age / 12; end
Ddef age_in_months; return age * 12; end
Step-by-Step Solution
Solution:
  1. Step 1: Use instance variable @age

    The age is stored in @age, so use it inside the method.
  2. Step 2: Multiply by 12 to get months

    Multiply the age in years by 12 to convert to months.
  3. Final Answer:

    def age_in_months; @age * 12; end -> Option A
  4. Quick Check:

    Use @age and multiply by 12 for months [OK]
Quick Trick: Instance variables start with @ and hold object data [OK]
Common Mistakes:
  • Using variable without @
  • Dividing instead of multiplying
  • Using undefined variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes