如果 ruby 如此鼓励鸭子输入,为什么我们不使用 Hash.count 而不是 Hash.length?
这确实让我感到困惑,似乎我一次又一次地遇到 ruby 本机数据类型中的方法,它们执行相同的操作(本质上),但具有不同的名称。如果 ruby 和 ruby 社区如此强烈鼓励鸭子类型,那么为什么这些方法的命名不跨类型一致呢?
This is something that really confuses me, it seems like time and time again I run into methods in ruby native data types that do the same thing (essentially), and yet have different names. If duck typing is so strongly encouraged by ruby and the ruby community, why aren't these methods named consistently across types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎暗示 Hash 没有
length
方法和/或其他可枚举没有count
方法。那不是真的。count
是在Enumerable
模块中定义的方法,因此可用于所有枚举。它与size
和length
的不同之处如下:O(n)
(当然总是在给定一个块时)。length
和size
(它们是同义词)是在所有可枚举类上定义的方法,用于跟踪其大小(包括Hash
)。它们与 count 的不同之处在于它们总是在O(1)
时间内返回长度并且不占用块。总之:您可以对任何跟踪其大小的对象调用
length
或size
,并且可以对任何可枚举对象调用count
。所以鸭子打字不会受到任何阻碍。You seem to imply that Hash does not have a
length
method and/or that other enumerables don't have acount
method. That is not true.count
is a method defined in theEnumerable
module and thus available on all enumerables. It differs fromsize
andlength
in the following ways:O(n)
for those that don't (and always when given a block of course).length
andsize
(which are synonyms) are methods defined on all enumerable classes that keep track of their size (includingHash
). They differ from count in that they always return the length inO(1)
time and don't take a block.In summary: You can call
length
orsize
on any object that keeps track of its size and you can callcount
on any enumerable. So duck typing is not hampered in any way.