0
0
Rubyprogramming~30 mins

Curry and partial application in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Curry and partial application
📖 Scenario: Imagine you run a small bakery. You want to create a simple way to calculate the price of different baked goods with tax included. Instead of writing the tax calculation every time, you will use a technique called currying to make your code cleaner and easier to reuse.
🎯 Goal: Build a Ruby program that uses currying to create a function for calculating the price of baked goods including tax. You will start by creating a basic price calculator, then use currying to fix the tax rate, and finally calculate prices for different items.
📋 What You'll Learn
Create a method called calculate_price that takes two arguments: tax_rate and price.
Create a curried version of calculate_price called curried_calculate_price.
Use partial application to fix the tax rate at 0.08 (8%) and create a new function called price_with_tax.
Calculate the price with tax for an item costing 100 using price_with_tax.
Print the final price with tax.
💡 Why This Matters
🌍 Real World
Currying and partial application help programmers write cleaner and reusable code, especially when some inputs stay the same across many calculations, like tax rates in pricing.
💼 Career
Understanding currying is useful in functional programming and can improve your ability to write modular, maintainable code in Ruby and other languages.
Progress0 / 4 steps
1
Create the basic price calculator method
Write a method called calculate_price that takes two parameters: tax_rate and price. It should return the total price including tax by calculating price + price * tax_rate.
Ruby
Need a hint?

Remember, a method in Ruby starts with def and ends with end. Use price + price * tax_rate to calculate the total.

2
Create a curried version of the method
Create a variable called curried_calculate_price that stores the curried version of the calculate_price method. Use the method(:calculate_price).to_proc.curry syntax.
Ruby
Need a hint?

Use method(:calculate_price).to_proc.curry to get the curried version of the method.

3
Fix the tax rate using partial application
Create a new variable called price_with_tax by calling curried_calculate_price with the tax rate fixed at 0.08 (8%).
Ruby
Need a hint?

Call curried_calculate_price with 0.08 to fix the tax rate.

4
Calculate and print the final price with tax
Use the price_with_tax function to calculate the price including tax for an item costing 100. Store the result in a variable called final_price. Then print final_price.
Ruby
Need a hint?

Call price_with_tax.call(100) to get the final price, then print it with puts.