How to usethe Keyword Arguments Syntax (Ruby 0+) in Ruby

Code:

Ruby
def greet(name: 'World')
  puts "Hello, #{name}!"
end

greet
# Output: Hello, World!

greet(name: 'Alice')
# Output: Hello, Alice!

Output
Hello, World!
Hello, Alice!

Explanation:

  • Ruby 2.0 introduced keyword arguments, allowing you to specify default values directly in the method signature.
  • This approach enhances code readability by explicitly naming the parameters when invoking the method.

How to set default arguments in Ruby?

Setting default arguments in Ruby allows you to define values that will be used when no argument is provided for a method parameter. This feature provides flexibility and enhances code readability.

Let’s explore various approaches to set default arguments in Ruby:

Table of Content

  • Approach 1: Using Default Parameter Values
  • Approach 2: Using Conditional Assignment
  • Approach 3: Using the Hash Argument Pattern
  • Approach 4: Using the Keyword Arguments Syntax (Ruby 2.0+)
  • Approach 5: Using the Proc Object as a Default Argument

Similar Reads

Approach 1: Using Default Parameter Values

Code:...

Approach 2: Using Conditional Assignment

Code:...

Approach 3: Using the Hash Argument Pattern

Code:...

Approach 4: Using the Keyword Arguments Syntax (Ruby 2.0+)

Code:...

Approach 5: Using the Proc Object as a Default Argument

Code:...