Ruby setter 习语
我正在开发一个 Chart
类,它有一个 margin
参数,其中包含 :top
、:bottom
、:right
和 :left
值。我的第一个选择是使 margin
成为一个 setter 并设置如下值:
# Sets :left and :right margins and doesn't alter :top and :bottom
chart.margins = {:left => 10, :right => 15}
这很好,因为它显然是一个 setter,但是,经过一番思考,我认为它也可能会令人困惑:用户可能会认为margins 仅包含 :left
和 :right
值,这是不正确的。另一种选择是消除 =
并使其成为普通方法:
chart.margins(:left => 10, :right => 15)
使用这种语法,很容易弄清楚发生了什么,但它不是标准设置器,并且与 margins
冲突吸气剂。还有另一种选择:
chart.margins(:left, 10)
chart.margins(:right, 15)
我不知道该怎么想。对我来说,很明显该方法是一个 setter,但这次我无法仅通过一次调用来设置多个值,并且 getter 再次出现问题。我对 Ruby 比较陌生,还没有习惯所有的习惯用法。那么,你们觉得怎么样?哪个是最好的选择?
I'm working on a Chart
class and it has a margin
parameter, that holds :top
, :bottom
, :right
and :left
values. My first option was to make margin
a setter and set values like this:
# Sets :left and :right margins and doesn't alter :top and :bottom
chart.margins = {:left => 10, :right => 15}
It's nice, because it is clearly a setter, but, after some thought, I think it could be confusing too: the user might think that margins contains only :left
and :right
values, what is not right. Another option is eliminate =
and make it an ordinary method:
chart.margins(:left => 10, :right => 15)
With this syntax, it's easy to figure out what is happening, but it is not a standard setter and conflicts with margins
getter. And there's still another option:
chart.margins(:left, 10)
chart.margins(:right, 15)
I don't know what to think about this. For me, it is obvious the method is a setter, but this time I cannot set multiple values with just one call and there's the problem with getter again. I'm relatively new to Ruby and I haven't got used to all the idioms yet. So, what do you think guys? Which is the best option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您还可以创建一个 Margin 类来享受以下清晰的语法:
You could also make a Margin class to enjoy the following clear syntax:
不太确定这是否是您想要提供的语法(如果不是,抱歉:)
Not so sure if this is the kind of syntax that you would like to make available (sorry if not : )
除了范例的答案之外,您还可以向 Margins 类添加一个方法来支持:
您可以扩展 margins= 方法来处理数字参数:
作为糖:
In addition to paradigmatic's answer, you could add a method to the Margins class to support:
You could extend the margins= method to treat a numeric argument:
as sugar for:
我不认为为 Margin 创建一个类是一种矫枉过正的做法。您始终可以使用
to_hash
或类似的方法将其值公开为哈希值。另外,如果你愿意,你可以让它以 DSL 风格工作:
但我想我无论如何都会选择范例的方法......
I don't think creating a class for Margin is an overkill. You can always expose its values as a hash using
to_hash
or something similar.Also, if you like, you can make it work in DSL-style:
But I guess I would choose paradigmatic's approach anyway...
您也可以坚持最初使用的内容并使用正常的哈希语法。
You could also stick with what you had first and use the normal hash syntax.