问题描述
Ruby 2.0.0支持关键字参数(KA),我想知道在纯Ruby上下文中此功能的好处/用例是什么,特别是从关键字匹配导致的性能损失来看,尤其如此每次调用带有关键字参数的方法时都可以完成.
Ruby 2.0.0 supports keyword arguments (KA) and I wonder what the benefits/use-cases are of this feature in context of pure Ruby, especially when seen in light of the performance penalty due to the keyword matching that needs to be done every time a method with keyword arguments is called.
require 'benchmark'
def foo(a:1,b:2,c:3)
[a,b,c]
end
def bar(a,b,c)
[a,b,c]
end
number = 1000000
Benchmark.bm(4) do |bm|
bm.report("foo") { number.times { foo(a:7,b:8,c:9) } }
bm.report("bar") { number.times { bar(7,8,9) } }
end
# user system total real
# foo 2.797000 0.032000 2.829000 ( 2.906362)
# bar 0.234000 0.000000 0.234000 ( 0.250010)
推荐答案
关键字参数具有一些独特的优点,没人能触及.
Keyword arguments have a few distinct advantages no one has touched on.
首先,您没有耦合到参数的顺序.因此,在有时候您可能会使用nil参数的情况下,它看起来要干净得多:
First off you are not coupled to the order of the arguments. So in a case where you might have a nil argument occasionally it looks a lot cleaner:
def yo(sup, whats="good", dude="!")
# do your thing
end
yo("hey", nil, "?")
如果您使用关键字参数:
if you use keyword arguments:
def yo(sup:, whats:"good", dude:"!")
# do your thing
end
yo(sup: "hey", dude: "?")
甚至
yo(dude: "?", sup: "hey")
它消除了必须记住参数顺序的需要.但是,缺点是您必须记住该参数的名称,但这应该或多或少是直观的.
It removes the need to have to remember the order of the arguments. However, the disadvantage is you have to remember the argument's name, but that should be more or less intuitive.
此外,当您有一个将来可能需要接受更多参数的方法时.
Also, when you have a method that could possibly have a need to take more arguments in the future.
def create_person(name:, age:, height:)
# make yourself some friends
end
如果您的系统突然想知道一个人最喜欢的糖果棒,或者他们超重(由于食用了太多他们喜欢的糖果棒)怎么办?简单:
what if your system all of the sudden wants to know about a person's favorite candy bar, or if they are overweight (from consuming too many of their favorite candy bar), how would you do that? Simple:
def create_person(name:, age:, height:, favorite_candy:, overweight: true)
# make yourself some fat friends
end
在关键字参数之前总是存在哈希,但是这导致了更多的样板代码来提取和分配变量.样板代码==更多键入==更多潜在错别字==减少编写超棒红宝石代码的次数.
Before keyword arguments there was always the hash, but that led to a lot more boilerplate code to extract and assign variable. Boilerplate code == more typing == more potential typos == less times writing awesome ruby code.
def old_way(name, opts={})
age = opts[:age]
height = opts[:height]
# all the benefits as before, more arthritis and headaches
end
如果您只是设置一个带有一个参数并且很可能永远不需要更改的方法:
If you are just setting up a method that takes one argument and will most likely never have a need to change:
def say_full_name(first_name, last_name)
puts "#{first_name} #{last_name}"
end
然后应避免使用关键字参数,因为这会对性能造成小的影响.
Then keyword arguments should be avoided, since there is a small performance hit.
这篇关于何时在Ruby中使用关键字参数(又名命名参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!