In Ruby, #length and #size are synonyms and both do the same thing: they tell you how many elements are in an array or hash. Technically #length is the method and
#size is an alias to it.
In ActiveRecord, there are several ways to find out how many records are in an association, and there are some subtle differences in how they work.
-
post.comments.count - Determine the number of elements with an SQL COUNT query. You can also specify conditions to count only a subset of the associated elements (e.g.
:conditions
=> {:author_name => "josh"}
). If you set up a counter cache on the association, #count will return that cached value instead of executing a new query.
-
post.comments.length - This always loads the contents of the association into memory, then returns the number of elements loaded. Note that this won't force an update if the association had been previously loaded and then new comments
were created through another way (e.g.
Comment.create(...)
instead
ofpost.comments.create(...)
).
-
post.comments.size - This works as a combination of the two previous options. If the collection has already been loaded, it will return its length just like calling #length. If it hasn't been loaded yet, it's like calling #count.
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
For arrays and hashessize
is
an alias forlength
.
They are synonyms and do exactly the same thing.
count
is
more versatile - it can take an element or predicate and count only those items that match.
> [1,2,3].count{|x| x > 2 }
=> 1
In the case where youdon'tprovide a parameter to count it has basically the same effect as calling length. There can be a performance difference though.
We can see from thesource
code for Arraythat they do almost exactly the same thing. Here is the C code for the implementation ofarray.length
:
static VALUE
rb_ary_length(VALUE ary)
{
long len = RARRAY_LEN(ary);
return LONG2NUM(len);
}
And here is the relevant part from the implementation ofarray.count
:
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..
}
}
The code forarray.count
does
a few extra checks but in the end calls the exact same code:LONG2NUM(RARRAY_LEN(ary))
.
Hashes (source
code) on the other hand don't seem to implement their own optimized version ofcount
so
the implementation fromEnumerable
(source
code) is used, which iterates over all the elements and counts them one-by-one.
In general I'd advise usinglength
(or
its aliassize
)
rather thancount
if
you want to know how many elements there are altogether.
分享到:
相关推荐
Status DeleteK(SqList &a,int ... if(va.length+1>va.listsize) return ERROR; va.length++; for(i=va.length-1;va.elem[i]>x&&i>=0;i--) va.elem[i+1]=va.elem[i]; va.elem[i+1]=x; return OK; }//Insert_SqList
if(va.length+1>va.listsize) return ERROR; va.length++; for(i=va.length-1;va.elem[i]>x&&i>=0;i--) va.elem[i+1]=va.elem[i]; va.elem[i+1]=x; return OK; }//Insert_SqList 2.12 int ListComp(SqList A...
java编的五子棋 import java.util.*; import java.io.*; import java.awt.*;... if(x+displace_x>=0 && x+displace_x<length && y+displace_y>=0 && y+displace_y<length && grid[x+displace_x][y+...
unsigned char Spi_Read_Packet(unsigned char *Rx_buffer,unsigned char length); void Spi_Write_Packet(unsigned char *Tx_buffer,unsigned char size) ; void Spi_Write_Burst(unsigned char addr,unsigned char...
Bitset(const std::string & str, size_t _Pos, size_t _Count); public: size_t size()const; //返回设置为1的位数 size_t count() const; bool subscript(size_t _Pos) const; bool get(size_t pos) const; ...
void update(const unsigned char *buf, size_type length); void update(const char *buf, size_type length); MD5& finalize(); std::string hexdigest() const; friend std::ostream& operator(std::ostream...
String countSql = "select count(*) from userinfo where 1=1"+conditionSql; pager.setTotalCount(getUserCount(countSql)); return list; } //查询条数 public int getUserCount(String sql){ int ...
* @return iteration count if one was specified, else 1. */ public int getLoopCount() { return loopCount; } /** * Creates new frame image from current data (and previous * frames as specified ...
strPDFMessage="trailer << /Size "+ (xRefs.Count+1)+" /Root 6 0 R >> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="startxref " + streamStart+" %%EOF "; ConvertToByteAndAddtoStream...
requestHeaders.Add("Content-Length", postStream.Length.ToString()); requestHeaders.Add("Content-Type", "application/x-www-form-urlencoded"); requestHeaders.Add("Connection", "close"); ...
for (int i = 0; i < files.Count;... size = Math.Round(fb.ContentLength/1024.0)+"KB"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } fb.SaveAs(path + fileName); }
$ i < count> length ); $ i ++) $ size += $ file -> length [ $ i ]; echo "-> Torrent info : \n" ; echo " -> CreatedBy : " . $ file -> createdBy . "\n" ; echo " -> CreationDate : " . $ file -> ...
selCity.length=count; } function Province_onchange() { FillCitys(g_selCity,g_selProvince.value); } function InitCitySelect(selProvince,selCity) { //alert("begin"); g_selProvince=selProvince...
1.5.6 string与count、count_if 15 1.6 string与wstring 15 1.6.1 简介 15 1.6.2 wstring实例 15 1.6.3 wstring与控制台 16 1.6.4 string与wstring的相互转换 17 1.7 string与C++流 22 1.7.1 C++流简介 22 1.7.2 ...
size() C. count() D. length() 下列关于Python变量的说法中,正确的是( ) A. 变量名必须以数字开头 B. 变量名区分大小写 C. 变量名可以使用Python关键字 D. 变量赋值后,其值不可改变 在Python中,以下哪个...
DWORD Count; DWORD Unk04; DWORD Unk08; } PROCESS_INFO_HEADER, *PPROCESS_INFO_HEADER; typedef struct _PROCESS_INFO { DWORD LoadAddress; DWORD Size; DWORD Unk08; DWORD Enumerator; ...
PIXELTYPEENUM_TYPECOUNT = 12 //"类型的数目" */ int pixelType; DPoint2 origin; DPoint2 finestResolution; IPoint2 finestSize;//最高level的栅格大小 IPoint2 blockSize; double lzts; int shareEdge...
length (cppstring) #line (preproc) localtime (stddate) log (stdmath) log10 (stdmath) longjmp (stdother) lower_bound (cppmap) lower_bound (cppmultimap) lower_bound (cppmultiset) lower_bound ...
}主要使用了 int substr_count ( string haystack, string needle [, int offset [, int length]] ) 这个方法,这个方法遍历待测的字符串$str中有没有$allergicWord数组中所包含的敏感词:
float MyFileSize = (float)MyFileInfo.Length / (1024 * 1024); this.labeMp3Size.Text = MyFileSize.ToString().Substring(0, 6) + "M"; } catch { this.labeMp3Size.Text = ""; } } //保存播放列表 ...