Alex Rivera | Logout

size, length and count in Rails

Asked 2012-09-03T19:46:27.770
27
1.9.3p194 :002 > u = User.find_by_email("email@mail.ru")
1.9.3p194 :005 > u.addresses.size
 => 1 
1.9.3p194 :006 > u.addresses.length
 => 1 
1.9.3p194 :007 > u.addresses.count 

There is no difference between size, length and count in Rails 3.2.3, isn't it?

Edit
Report

1 Answer

2

If "addresses" is an association which it looks like, then they are different but they should return the same result.

#count is provided by ActiveRecord and will execute something like "select count(*) from addresses where user_id = ".

In the other cases, #addresses will build an array containing actual model objects and #size and #length are provided by the Array class or maybe Enumerable.

So #count is probably faster, because the counting happens in the database. Not much good if you actually need the addresses tho :)

answered 2012-09-04T04:49:24.843

Your Answer