繁体   English   中英

在Ruby中对数组元素进行计数(count()函数产生意外结果)

[英]Counting array elements in Ruby (unexpected results by the count( ) function)

以我的理解,以下ruby表达式应产生相同的结果。
显然我遗漏了一些东西,这是一种非常严重的错误,不被忽视。

# returns the number of ALL elements in the array
count = @quotation.quotation_items.count { |x| x.placement == current_placement}

# Does what I expect
count = (@quotation.quotation_items.find_all { |x| x.placement == current_placement }).length

上面的quotation_items是一个ActiveRecord has_many关联

#count不会像这样阻塞。

如果要按条件使用条件,则可以执行以下操作:

@quotation.quotation_items.count(:conditions => "placement = #{current_placement}")

http://apidock.com/rails/ActiveRecord/Calculations/ClassMethods/count

如果您使用的是ActiveRecord,则需要牢记在某个点上它正在为查询编译条件和子句,在某个位置上您可以得到一个结果集。 某些事物只能在一种模式或另一种模式下工作,尽管它试图使事物保持一致。

在您的情况下,您希望count可以像Enumerable一样工作,但这仍然是数据库级的运算符。

要解决此问题:

@quotation.quotation_items.where(placement: current_placement).count

这构成了一个查询,该查询仅计算您需要的东西,大约是:

SELECT COUNT(*) FROM quotation_items WHERE quotation_id=? AND placement=?

那是产生一个数字的东西,与选择每条记录,实例化为模型,然后使用Enumerable进行计数的方法大不相同。

您使用的#count错误。

我相信它不会接受封锁。 我不确定为什么它没有返回错误。

您可以像这样使用它:

count = @quotation.quotation_items.map{ |x| x.placement == current_placement}.count(true)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM