Keyword (Named) Parameters

Introduced in Ruby 2.0, keyword parameters provide a way to pass arguments to a method by explicitly specifying parameter names and their corresponding values. This feature proves valuable, especially in scenarios involving methods with numerous parameters, as it significantly enhances code readability and clarity.

Example Usage:

# A demonstration of keyword parameters in action
def keyword_params(a:, b: 3, c:)
  puts a + b + c
end

# Example calls with specified values
keyword_params(a: 1, b: 2, c: 3)  # Output: 6
keyword_params(a: 0, c: 0)        # Output: 3
keyword_params(a: 0, b: 40, c: 0) # Output: 40

Definition:

When defining a method, keyword parameters can be specified using the colon (`:`) syntax, providing a more explicit way to declare parameters:

# The traditional way with positional parameters
def old_way(foo, bar)
  puts foo + bar
end
old_way(1, 2) # Output: 3

# The new way with keyword parameters
def new_way(foo:, bar:)
  puts foo + bar
end
new_way(foo: 1, bar: 2) # Output: 3

In the example calls, the method `keyword_params` showcases the flexibility of keyword parameters, allowing you to specify default values (`b: 3`) and omit certain parameters when calling the method. The subsequent definition examples illustrate the contrast between the traditional method with positional parameters (`old_way`) and the modern approach using keyword parameters (`new_way`). This syntax provides improved clarity and explicitness when working with methods that have multiple parameters.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *