- Comprehensive Ruby Programming
- Jordan Hudgens
- 359字
- 2025-04-04 18:58:15
Named arguments
Additionally, Ruby gives us the ability to name our arguments. This can be helpful when you have method signatures with a number of arguments and you want the method calls to be explicit. Here is how you can use named arguments in Ruby:
def print_address city:, state:, zip:
puts city
puts state
puts zip
end
print_address city: "Scottsdale", state: "AZ", zip: "85251"
If you run this code, it will work properly.

So why are named arguments helpful? I think the easiest way to answer that question is to update our code and remove the named components. That code would look like this:
def print_address city, state, zip
puts city
puts state
puts zip
end
print_address "Scottsdale", "AZ", "85251"
If you run this code, it will work exactly as it did earlier.

However, by removing the named arguments, we've made our method more difficult to work with and more prone to bugs. When working with a method as simple as print_address, it's easy to know what the city, state, and zip parameters represent and to provide them in that order. However, what if we had a method that looked like this:
def sms_generatorapi_key, num, msg, locale
# Magic SMS stuff...
end
In a case like this, we would have to reference the method declaration several times to ensure we're passing in the arguments properly. See what would happen if we tried to call this method with the code:
sms_generator "82u3ojerw", "hey there", 5555555555, 'US'
Nothing looks wrong with this code, right? Actually, this code won't work because we've accidentally swapped the order of the phone number and message. In a real application, the method would try to send the SMS to the hey there string, which wouldn't work for obvious reasons.
However, if we update this method to use named arguments, the order no longer matters:
def sms_generatorapi_key:, num:, msg:, locale:
# Magic SMS stuff...
end
sms_generatorapi_key: "82u3ojerw", msg: "hey there", num: 5555555555, locale: 'US'
When you utilize named arguments, you don't have to worry about the order that you pass the arguments in, which is a nice convenience and will also help prevent bugs in your program.