哈希与多个参数?
在 Ruby 中,接收参数哈希值而不是仅仅将参数传递给方法的方法很常见。
我的问题是 - 什么时候在方法中使用参数以及什么时候使用参数哈希?
当方法具有超过一两个参数时,使用参数哈希是一种好的做法吗?
It is very common in Ruby to see methods that receive a hash of parameters instead of just passing the parameters to the method.
My question is - when do you use parameters for your method and when do you use a parameters hash?
Is it right to say that it is a good practice to use a parameter hash when the method has more than one or two parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
每当参数哈希代表一组语义上属于在一起的选项时,我都会使用参数哈希。对于函数的直接(通常是必需的)参数的任何其他参数,我都会一一传递。
I use parameter hashes whenever they represent a set of options that semantically belong together. Any other parameters which are direct (often required) arguments to the function, I pass one by one.
当有许多可选参数时,或者当您想要接受任意参数时,您可能需要使用哈希,正如您在许多 Rails 方法中看到的那样。
You may want to use a hash when there are many optional params, or when you want to accept arbitrary params, as you can see in many rails's methods.
如果您有超过 2 个争论。你应该开始考虑使用哈希。
这是良好的做法,在干净的代码中清楚地解释了链接文本
if you have more than 2 arguements. you should start thinking of using hash.
This is good practise clearly explained in clean code link text
一个明显的用例是,当您重写子类中的方法时,您应该在调用父方法时使用哈希参数作为父方法的参数。
One obvious use case is when you are overriding a method in a child class, you should use hash parameters for the parent method's parameters for when you call it.
另一方面,这不仅与 Ruby 有关,而且与所有语言有关:
在不断变化的 API 中,有时将函数的部分或全部参数声明为单个参数对象很有用(在 Ruby 中,这些参数可以是哈希值,在 C 结构体中,等等),以便在未来版本中接受的参数集发生变化时保持 API 稳定性。然而,明显的缺点是可读性大大降低,除非我真的必须这样做,否则我永远不会使用这种“模式”。
On another note, and this is not only related to Ruby but to all languages:
In APIs which are in flux, it is sometimes useful to declare some or all parameters to a function as a single parameters object (in Ruby these could be hashes, in C structs, and so on), so as to maintain API stability should the set of accepted arguments change in future versions. However, the obvious downside is that readability is drastically reduced, and I would never use this "pattern" unless I'd really really have to.