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

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.

主站蜘蛛池模板: 小金县| 石首市| 新绛县| 犍为县| 临颍县| 邹平县| 浏阳市| 射洪县| 盐池县| 沙雅县| 阿坝县| 定远县| 额尔古纳市| 鹤峰县| 从化市| 武宁县| 苏尼特右旗| 涟水县| 汉川市| 滦平县| 定边县| 新安县| 呼图壁县| 泸州市| 滁州市| 道孚县| 寿阳县| 临桂县| 山阴县| 江西省| 尼玛县| 邢台县| 资溪县| 罗城| 嘉定区| 四会市| 开阳县| 合山市| 治多县| 深泽县| 龙泉市|