上一篇翻译了 Ruby Rails中 .nil? .empty? .blank? 方法区别 之后, 我又觉得这种横向比较的方式是非常有用的.
这次我本人遇到的困惑是 count size length 这些计数类\维度计算类方法的使用. 参考了stackoverflow中的一个问题:
http://stackoverflow.com/questions/4550770/count-size-length-too-many-choices-in-ruby
首先看下面的例子:
a = { "a" => "Hello", "b" => "World" }
a.count # 2
a.size # 2
a.length # 2
a = [ 10, 20 ]
a.count # 2
a.size # 2
a.length # 2
我对后面的回答作些解释
Array数组中提供了length size 实际上是相同的. 而count也可被array来调用. 不过它的功能更强大, 例如:
a.count {|x| x>2}
比较这几个方法的源代码:
static VALUE
rb_ary_length(VALUE ary)
{
long len = RARRAY_LEN(ary);
return LONG2NUM(len);
}
static VALUE
rb_ary_count(int argc, VALUE *argv, VALUE ary)
{
long n = 0;
if (argc == 0) {
VALUE *p, *pend;
if (!rb_block_given_p())
return LONG2NUM(RARRAY_LEN(ary));
// etc..
}
}
能看到count的参数列表与length不同, 具有更强大的功能.
总结:
大多数情况下(数组或字符串) size是length方法的另一种别名.
In most cases (e.g. Array or String) size
is an alias for length
.
另一篇参考资料
http://blog.hasmanythrough.com/2008/2/27/count-length-size