How to useConditional Assignment in Ruby
Code:
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.
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