Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
97: The Strategy Pattern in Ruby
Imagine you're building a travel app. The user wants to get to the airport, but they have options: they could take an Uber, a city bus, or a train. Regardless of the choice, the end goal is the same—they arrive at the terminal. However, the way they get there (the cost, the time, the process) is completely different for each method.
In programming, we often fall into the trap of handling these options with a giant case statement or a string of if/else blocks. It looks something like this: if transport == 'uber' then ... elsif transport == 'bus' then .... That works for two options, but once you add shuttles, bikes, and walking, your method becomes a bloated monster that's a nightmare to test.
The Strategy Pattern is how we fix that. Instead of one method trying to know every possible way to do something, we move each "way" into its own object. The main class doesn't care how the work is done; it just knows that whatever object it's holding has a method it can call to get the result.
Escaping the Giant Case Statement
Let's look at a real scenario: a shipping calculator for an e-commerce store. You start with FedEx, and then you add UPS. Then DHL. Then a local courier. If you keep adding these to a single ShippingCalculator class, it'll eventually collapse under its own weight.
Instead, we define a "Strategy" for each carrier. In Ruby, we don't need formal interfaces because we have duck typing. As long as every strategy object responds to the same method—let's call it calculate—the main calculator doesn't need to know which carrier it's actually using.
class FedExStrategy
def calculate(weight)
weight * 1.5 + 10
end
end
class UPSStrategy
def calculate(weight)
weight * 1.2 + 15
end
end
class LocalCourierStrategy
def calculate(weight)
weight * 2.0 # Flat rate per kg, no base fee
end
end
Connecting the Strategy to the Context
Now we need a "Context" class. This is the object the rest of your app interacts with. It doesn't contain the math; it just holds a reference to one of the strategies we wrote above. I like to pass the strategy in through the initializer, which makes it incredibly easy to swap out during testing.
class ShippingCalculator
attr_accessor :strategy
def initialize(strategy)
@strategy = strategy
end
def total_cost(weight)
# The calculator doesn't care which strategy is active.
# It just trusts that @strategy responds to :calculate.
@strategy.calculate(weight)
end
end
Here is where the magic happens. You can change the behavior of your calculator at runtime without changing a single line of code inside the ShippingCalculator class:
# Start with FedEx
calc = ShippingCalculator.new(FedExStrategy.new)
puts calc.total_cost(10) # 25.0
# User changes their mind to UPS
calc.strategy = UPSStrategy.new
puts calc.total_cost(10) # 27.0
Why This Actually Matters in Production
You might be thinking, "Isn't this just more classes for the sake of more classes?" I used to think that too. But consider this: when you need to add a new carrier (like DHL), you don't have to touch the ShippingCalculator class at all. You just create a DHLStrategy class and pass it in.
This follows the Open/Closed Principle: your code is open for extension (adding new strategies) but closed for modification (you aren't risking breaking existing logic by editing a 500-line case statement). It turns a risky modification into a safe addition.
📋 Practical Task
Build a Pluggable Payment Processor
You are building a checkout system that needs to support multiple payment gateways. Currently, the system only supports Credit Card payments, but you need to make it flexible enough to add PayPal and Bitcoin without modifying the main checkout logic.
Your Task:
- Create a
PaymentProcessorclass (the Context) that accepts a strategy object in its initializer and has a methodprocess_payment(amount). - Create three strategy classes:
CreditCardPayment,PayPalPayment, andBitcoinPayment. - Each strategy should implement a
pay(amount)method that prints a specific message (e.g., "Processing $100 via Credit Card..."). - Demonstrate the Strategy Pattern by instantiating the
PaymentProcessorwith one strategy, processing a payment, and then swapping the strategy to a different gateway to process another payment.
There are no comments for now.