Open In App

How to set default arguments in Ruby?

Last Updated : 25 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Approach 1: Using Default Parameter Values

Code:

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

greet
# Output: Hello, World!

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

Explanation:

  • In this approach, you can specify default values directly in the method definition.
  • If no argument is provided when invoking the method, the default value will be used.

Approach 2: Using Conditional Assignment

Code:

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

greet
# Output: Hello, World!

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

Output
Hello, World!
Hello, Alice!

Explanation:

  • Using conditional assignment, you can check if the argument is nil and assign a default value if it is.
  • This approach provides more flexibility in determining the default value based on certain conditions.

Approach 3: Using the Hash Argument Pattern

Code:

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

greet
# Output: Hello, World!

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

Output
Hello, World!
Hello, Alice!

Explanation:

  • In this approach, you can use a hash argument to specify default values for method parameters.
  • The fetch method allows you to retrieve the value associated with the :name key from the options hash, using the default value ‘World’ if the key is not present.

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

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.

Approach 5: Using the Proc Object as a Default Argument

Code:

Ruby
def greet(name = -> { 'World' })
  puts "Hello, #{name.call}!"
end

greet
# Output: Hello, World!

greet(-> { 'Alice' })
# Output: Hello, Alice!

Output
Hello, World!
Hello, Alice!

Explanation:

  • This approach allows you to set a default value using a Proc object, providing flexibility in defining default values dynamically.
  • The call method is used to invoke the Proc object and retrieve the default value.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads