- Comprehensive Ruby Programming
- Jordan Hudgens
- 359字
- 2021-07-02 21:13:33
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.
- Kali Linux Web Penetration Testing Cookbook
- Android應用程序開發與典型案例
- 移動UI設計(微課版)
- 少年輕松趣編程:用Scratch創作自己的小游戲
- 深入淺出Prometheus:原理、應用、源碼與拓展詳解
- 認識編程:以Python語言講透編程的本質
- Web Application Development with R Using Shiny(Second Edition)
- Building a Recommendation Engine with Scala
- Kotlin Standard Library Cookbook
- CouchDB and PHP Web Development Beginner’s Guide
- Learning Zurb Foundation
- Apache Kafka Quick Start Guide
- PHP+MySQL+Dreamweaver動態網站開發從入門到精通(第3版)
- Mastering Linux Security and Hardening
- 算法圖解