Count, size, length…too many choices in Ruby?

前端 未结 6 509
逝去的感伤
逝去的感伤 2021-01-29 20:18

I can\'t seem to find a definitive answer on this and I want to make sure I understand this to the \"n\'th level\" :-)


    a = { \"a\" => \"Hello\", \"b\" => \"Worl         


        
6条回答
  •  终归单人心
    2021-01-29 20:49

    I found a good answare at http://blog.hasmanythrough.com/2008/2/27/count-length-size

    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.

    Also I have a personal experience:

    <%= h(params.size.to_s) %> # works_like_that !
    <%= h(params.count.to_s) %> # does_not_work_like_that !
    

提交回复
热议问题