Bird
0
0

You want to define a method that calculates the total price with tax. The tax rate should default to 0.1 (10%) if not provided. Which method definition correctly achieves this?

hard📝 Application Q8 of 15
Ruby - Methods
You want to define a method that calculates the total price with tax. The tax rate should default to 0.1 (10%) if not provided. Which method definition correctly achieves this?
Adef total_price(price, tax_rate = 0.1) price + price * tax_rate end
Bdef total_price(price, tax_rate) tax_rate ||= 0.1 price + price * tax_rate end
Cdef total_price(price, tax_rate = ) price + price * tax_rate end
Ddef total_price(price, tax_rate = 10) price + price * tax_rate end
Step-by-Step Solution
Solution:
  1. Step 1: Check default parameter syntax and value

    def total_price(price, tax_rate = 0.1) price + price * tax_rate end correctly sets tax_rate default to 0.1 using parameter = value syntax.
  2. Step 2: Evaluate other options

    def total_price(price, tax_rate) tax_rate ||= 0.1 price + price * tax_rate end uses fallback inside method body, which works but is not default parameter. def total_price(price, tax_rate = ) price + price * tax_rate end has invalid empty default. def total_price(price, tax_rate = 10) price + price * tax_rate end sets tax_rate to 10 (1000%), which is incorrect.
  3. Final Answer:

    def total_price(price, tax_rate = 0.1) ... -> Option A
  4. Quick Check:

    Use parameter = default_value for defaults [OK]
Quick Trick: Set default tax as parameter = 0.1 for clarity [OK]
Common Mistakes:
  • Leaving default value empty
  • Using incorrect default values
  • Using fallback inside method instead of default parameter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes