Bird
0
0

Given a hash data = {name: "Eve", age: 28, city: "NY"}, how can you create an OpenStruct object and then add a new property country with value "USA" dynamically?

hard📝 Application Q15 of 15
Ruby - Metaprogramming Fundamentals
Given a hash data = {name: "Eve", age: 28, city: "NY"}, how can you create an OpenStruct object and then add a new property country with value "USA" dynamically?
Aperson = OpenStruct.new(data); person.country = "USA"
Bperson = OpenStruct.new; person = data; person.country = "USA"
Cperson = OpenStruct.new(data); person[:country] = "USA"
Dperson = OpenStruct.new; person.add(:country, "USA")
Step-by-Step Solution
Solution:
  1. Step 1: Initialize OpenStruct with existing hash

    Use OpenStruct.new(data) to create an object with properties from the hash.
  2. Step 2: Add new property dynamically

    Assign new property with dot notation: person.country = "USA".
  3. Step 3: Check incorrect options

    person = OpenStruct.new; person = data; person.country = "USA" overwrites person with hash, losing OpenStruct. person = OpenStruct.new(data); person[:country] = "USA" uses []= which is invalid. person = OpenStruct.new; person.add(:country, "USA") uses a non-existent method add.
  4. Final Answer:

    person = OpenStruct.new(data); person.country = "USA" -> Option A
  5. Quick Check:

    Initialize with hash + dot assign new property [OK]
Quick Trick: Initialize with hash, add properties by dot assignment [OK]
Common Mistakes:
  • Overwriting OpenStruct with hash
  • Using []= to add properties
  • Calling non-existent methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes