0
0
Rubyprogramming~5 mins

Hash as named parameters pattern in Ruby

Choose your learning style9 modes available
Introduction

This pattern helps you pass many options to a method clearly and flexibly using a hash. It makes your code easier to read and change.

When a method needs many optional settings.
When you want to call a method with clear labels for each argument.
When you want to add new options later without changing the method call everywhere.
When you want to group related parameters together.
When you want to avoid remembering the order of many arguments.
Syntax
Ruby
def method_name(options = {})
  # use options[:key] to access values
end

# calling the method
method_name(key1: value1, key2: value2)

The method receives a hash named options with keys and values.

You access each option inside the method using options[:key].

Examples
This method uses a hash to get the name. If no name is given, it says "friend".
Ruby
def greet(options = {})
  name = options[:name] || "friend"
  puts "Hello, #{name}!"
end

greet(name: "Alice")
greet
Here, the method uses two named parameters inside a hash with defaults.
Ruby
def order_drink(options = {})
  size = options[:size] || "medium"
  type = options[:type] || "coffee"
  puts "Ordering a #{size} #{type}."
end

order_drink(size: "large", type: "tea")
order_drink(type: "juice")
Sample Program

This program shows a method that takes a hash as named parameters to book flights. It uses default values if some keys are missing.

Ruby
def book_flight(options = {})
  from = options[:from] || "Unknown"
  to = options[:to] || "Unknown"
  date = options[:date] || "Anytime"
  puts "Booking flight from #{from} to #{to} on #{date}."
end

book_flight(from: "NYC", to: "LA", date: "2024-07-01")
book_flight(to: "Paris")
OutputSuccess
Important Notes

You can use options.fetch(:key, default) to provide defaults more cleanly.

Since Ruby 2.0, you can also use real named parameters, but hashes are still useful for flexible options.

Summary

Use a hash to pass named parameters for clarity and flexibility.

Access options inside the method with options[:key].

Provide default values to handle missing keys.