上一篇翻譯了 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