简体   繁体   中英

How do I count items in an array that have a specific attribute value?

In my application, I have an array named @apps which is loaded by ActiveRecord with a record containing the app's name, environment, etc.

I am currently using @apps.count to get the number of apps in the array, but I am having trouble counting the number of applications in the array where the environment = 0 .

I tried @apps.count(0) but that didn't work since there are multiple fields for each record.

I also tried something like @apps.count{ |environment| environment = 0} @apps.count{ |environment| environment = 0} but nothing happened.

Any suggestions?

Just use select to narrow down to what you want:

@apps.select {|a| a.environment == 0}.count

However, if this is based on ActiveRecord, you'd be better off just making your initial query limit it unless of course you need all of the records and are just filtering them in different ways for different purposes.

I'll assume your model is call App since you are putting them in @apps :

App.where(environment: 0).count

You have the variable wrong. Also, you have assignment instead of comparison.

 @apps.count{|app| app.environment == 0}

or

 @apps.count{|app| app.environment.zero?}

I would use reduce OR each_with_object here:

reduce docs :

@apps.reduce(Hash.new(0)) do |counts, app| 
  counts[app.environment] += 1
  counts
end

each_with_object docs :

@apps.each_with_object(Hash.new(0)) do |app, counts| 
  counts[app.environment] += 1
end

If you are able to query, use sql

App.group(:environment).count will return a hash with keys as environment and values as the count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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