Ruby-on-rails array.count 和 array.size 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4396476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:51:06  来源:igfitidea点击:

Difference between array.count and array.size

ruby-on-railsarrays

提问by ssri

Is there any difference between array.countand array.size?

有什么区别array.countarray.size

I am getting errors sometimes on production environment while using array.count, but the same works fine when I use array.size.

我在生产环境中有时会收到错误,同时使用array.count,但同样的作品很好,当我使用array.size

回答by Simone Carletti

Starting from Ruby 1.8.7, Array#countis the same of Array#size.

从 Ruby 1.8.7 开始,Array#countArray#size.

Please note that Array#countdoesn't exist in Ruby versions lower than 1.8.7 so if you are running Ruby 1.8.6 in production, it will raise a NoMethodError.

请注意,Array#count在低于 1.8.7 的 Ruby 版本中不存在,因此如果您在生产中运行 Ruby 1.8.6,它将引发NoMethodError.

Also, make sure you are talking about arrays. In ActiveRecord, for example, #sizeand #countare slightly different. #sizeunderstands caching like counter cache, while count doesn't.

另外,请确保您在谈论数组。例如,在 ActiveRecord 中,#size#count略有不同。#size像计数器缓存一样理解缓存,而 count 不理解。