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

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.

主站蜘蛛池模板: 庆云县| 庆阳市| 泸定县| 左贡县| 乌鲁木齐县| 玉林市| 揭阳市| 镇坪县| 凤翔县| 铜鼓县| 海南省| 云梦县| 马尔康县| 茂名市| 民县| 黑山县| 和田县| 望城县| 杭锦后旗| 江孜县| 芜湖市| 水富县| 灵璧县| 武鸣县| 望江县| 山阳县| 东山县| 马公市| 巢湖市| 屏山县| 阿拉善左旗| 施甸县| 沅陵县| 西充县| 新和县| 同江市| 罗田县| 沐川县| 兰州市| 芦溪县| 吉隆县|