Ruby’s #length vs #size vs #count Methods

Before googling for the article, I knew going in that .size is an alias to .length. But I didn’t know there was more to the story. And what about .count?

Here’s what Josh Susser wrote verbatim:

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 of post.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.