Bird
0
0

You want to write a method that accepts named parameters for :title, :author, and :year, but only :title is required. How would you define this method using a hash as named parameters?

hard📝 Application Q8 of 15
Ruby - Hashes
You want to write a method that accepts named parameters for :title, :author, and :year, but only :title is required. How would you define this method using a hash as named parameters?
Adef book_info(options = {}) "#{options[:title]} by #{options[:author]}, #{options[:year]}" end
Bdef book_info(title, author = nil, year = nil) "#{title} by #{author}, #{year}" end
Cdef book_info(title:, author: nil, year: nil) "#{title} by #{author}, #{year}" end
Ddef book_info(title: nil, author: nil, year: nil) "#{title} by #{author}, #{year}" end
Step-by-Step Solution
Solution:
  1. Step 1: Use keyword arguments for required and optional params

    title: is required (no default), author: and year: have nil defaults.
  2. Step 2: Confirm method signature matches requirements

    def book_info(title:, author: nil, year: nil) "#{title} by #{author}, #{year}" end uses keyword arguments correctly with required title.
  3. Final Answer:

    def book_info(title:, author: nil, year: nil)\n "#{title} by #{author}, #{year}"\nend -> Option C
  4. Quick Check:

    Required keyword param = title: without default [OK]
Quick Trick: Use keyword args with defaults for optional params [OK]
Common Mistakes:
  • Using hash with no required keys
  • Using positional arguments instead of keywords
  • Setting required keys with nil default

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes