Bird
0
0

Which of the following is the correct syntax to use dig on a hash h = {a: {b: 2}} to get the value 2?

easy📝 Syntax Q12 of 15
Ruby - Hashes
Which of the following is the correct syntax to use dig on a hash h = {a: {b: 2}} to get the value 2?
Ah.dig(:a).dig(b)
Bh.dig[:a][:b]
Ch[:a].dig(b)
Dh.dig(:a, :b)
Step-by-Step Solution
Solution:
  1. Step 1: Check the correct method call syntax

    The dig method is called with arguments representing the nested keys or indexes, separated by commas inside parentheses.
  2. Step 2: Validate each option

    h.dig(:a, :b) uses h.dig(:a, :b), which is the correct syntax. h.dig[:a][:b] uses square brackets incorrectly. h[:a].dig(b) uses b without the leading colon :, causing NameError. h.dig(:a).dig(b) chains dig calls unnecessarily and uses b without :, causing NameError.
  3. Final Answer:

    h.dig(:a, :b) -> Option D
  4. Quick Check:

    dig called with keys as arguments [OK]
Quick Trick: Use parentheses and commas for dig keys: dig(:a, :b) [OK]
Common Mistakes:
  • Using square brackets after dig
  • Chaining dig calls unnecessarily
  • Forgetting colons for symbol keys in dig

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes