Bird
0
0

Given nested hashes, which style guide compliant Ruby code flattens keys into a single-level hash with combined keys separated by underscores?

hard📝 Application Q9 of 15
Ruby - Ecosystem and Best Practices
Given nested hashes, which style guide compliant Ruby code flattens keys into a single-level hash with combined keys separated by underscores?
Anested = {a: {b: 1}} flat = nested.flatten
Bnested = {a: {b: 1}} flat = {} nested.each { |k,v| v.each { |k2,v2| flat["#{k}_#{k2}"] = v2 } }
Cnested = {a: {b: 1}} flat = nested.map { |k,v| [k, v] }.to_h
Dnested = {a: {b: 1}} flat = nested.reduce({}) { |h,(k,v)| h.merge(v) }
Step-by-Step Solution
Solution:
  1. Step 1: Understand flattening nested hashes

    We want keys combined with underscore and values preserved.
  2. Step 2: Check which code combines keys properly

    nested = {a: {b: 1}} flat = {} nested.each { |k,v| v.each { |k2,v2| flat["#{k}_#{k2}"] = v2 } } iterates nested hashes and creates combined keys correctly.
  3. Final Answer:

    nested = {a: {b: 1}}\nflat = {}\nnested.each { |k,v| v.each { |k2,v2| flat["#{k}_#{k2}"] = v2 } } -> Option B
  4. Quick Check:

    Nested each loops combine keys with underscores [OK]
Quick Trick: Use nested each loops to flatten hashes with combined keys [OK]
Common Mistakes:
  • Using flatten method on hash
  • Incorrect merge usage
  • Not combining keys properly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes