在构造函数中使用 splat 运算符是否有效?
在构造函数中,经常需要将参数转换为实例变量。一个简单的方法是:
class A
def initialize a, b, c
@a, @b, @c = a, b, c
end
end
但更简单的方法是:
class A
def initialize *args
@a, @b, @c = args
end
end
但我担心代码的速度,因为它看起来后面的代码正在创建一个额外的数组 args
,该数组不是在以前的代码。从速度或效率的角度来看,是坚持前一种而不使用后一种更好,还是没有区别?
In a constructor, it often happens that you want to turn the arguments into instance variables. A naive way to do it is:
class A
def initialize a, b, c
@a, @b, @c = a, b, c
end
end
but an easier way is:
class A
def initialize *args
@a, @b, @c = args
end
end
But I was concerned about the speed of the code since it looks like the latter code is creating an extra array args
that was not created in the former code. From the point of view of the speed or efficienty, is the better to stick to the former one and not use the latter one, or is there no difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从这里看起来不错:
Looks fine from here: