Bird
0
0

You want to write a method that accepts any number of arguments and returns a hash where keys are the arguments and values are their types as strings. Which method correctly does this?

hard📝 Application Q8 of 15
Ruby - Methods
You want to write a method that accepts any number of arguments and returns a hash where keys are the arguments and values are their types as strings. Which method correctly does this?
Adef types_hash(*args) args.to_h { |a| [a, a.class] } end
Bdef types_hash(*args) args.map { |a| [a, a.class.to_s] }.to_h end
Cdef types_hash(*args) args.each { |a| [a, a.class.to_s] } end
Ddef types_hash(*args) args.collect { |a| a.class } end
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to create a hash from an array

    Using map to create pairs and then to_h converts to a hash.
  2. Step 2: Evaluate each option

    def types_hash(*args) args.map { |a| [a, a.class.to_s] }.to_h end correctly maps each argument to a pair [argument, type string] and converts to hash. def types_hash(*args) args.to_h { |a| [a, a.class] } end does not convert class to string. def types_hash(*args) args.each { |a| [a, a.class.to_s] } end uses each which returns original array, not hash. def types_hash(*args) args.collect { |a| a.class } end returns array of classes, not a hash.
  3. Final Answer:

    def types_hash(*args) args.map { |a| [a, a.class.to_s] }.to_h end -> Option B
  4. Quick Check:

    Use map + to_h to build hash from *args [OK]
Quick Trick: Use map to create pairs, then to_h to build hash [OK]
Common Mistakes:
  • Using each instead of map for transformation
  • Incorrect block syntax with to_h
  • Returning array instead of hash

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes