Last Updated: February 25, 2016
·
515
· erol

Method parameter values as defaults of other optional parameters

We can define optional parameters with default values in Ruby:

def validate(username, options = {})
  options
end

validate 'user'
=> {}

But did you know that we can also define the default value of an optional parameter using the value of another parameter?

def welcome(username, domain, email = "#{username}@#{domain}")
  email
end

welcome 'user', 'host.com'
=> 'user@host.com'