有没有办法强制使用命名参数而不是标准 function_name(var, var)?
我真的很喜欢命名参数,因为它们极大地提高了代码的可读性。
Ruby 使用带有哈希值的伪命名参数,我已经使用该技术实现了一些方法,但是将这三行添加到每个带有参数的方法会变得很麻烦:
def something_does_something_with(parameters = {})
default_params = {:some => option, :another => something}
parameters = default_params.merge(parameters)
...
end
或者方法头可能是这样的:
def something_does_something_with(parameters = {:some => option, :another => something})
但是我想如果我提供任何参数,它都会覆盖整个默认哈希。
当我使用 Objective-C 时,命名变量是编程世界中我最喜欢的东西。
有没有办法修改 Ruby 查看方法头的默认方式,以便需要命名参数,或者至少更容易?
I really like named parameters, as they greatly help with the readability of my code.
Ruby uses pseudo-named parameters with hashes, and I've implemented a few methods using that technique, but adding these three lines to every method with parameters would get cumbersome:
def something_does_something_with(parameters = {})
default_params = {:some => option, :another => something}
parameters = default_params.merge(parameters)
...
end
or the method header could be like this:
def something_does_something_with(parameters = {:some => option, :another => something})
but then I think if I supply any parameters at all, it overrides the entire default hash.
When I worked with Objective-C, named-variables were my favorite thing in the programming universe.
Is there a way to modify the default way Ruby looks at method headers such that named-parameterss are required, or at least easier?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您绝对不能使用第二个示例,因为它仅在您传递全套参数时才有效。
参考您的第一个示例,您可以这样简短:
最后,命名参数计划在下一个版本的 Ruby - Ruby 2.0 中实现
You definitely can not use second example because it will work only in case when you're passing a full set of parameters.
In reference to your first example you could make it short like this:
And finally, the named parameters is planning to implement in the next version of Ruby - Ruby 2.0