官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 永泰县| 甘孜县| 阜南县| 洛隆县| 陵水| 柏乡县| 武鸣县| 胶州市| 广平县| 宁蒗| 平武县| 宜兴市| 突泉县| 江津市| 信丰县| 桦甸市| 枝江市| 扬州市| 沅江市| 乌恰县| 阿拉善左旗| 栖霞市| 合阳县| 安陆市| 客服| 周口市| 鄯善县| 登封市| 易门县| 酒泉市| 正镶白旗| 奈曼旗| 镇江市| 句容市| 乌海市| 新昌县| 玉树县| 鄂温| 天水市| 施甸县| 涟水县|