10

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} but nothing happened.

Any suggestions?

3 Answers 3

24

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
Sign up to request clarification or add additional context in comments.

2 Comments

I am going with the first solution because i need all of the records.
Depending on the number of records, it can be faster to ask the DBM to count the records, then iterating one record at a time, than it is to ask for all records, then count and iterate over them in Ruby. The DBM is optimized for handing a count and then iterating row-by-row. Dumping an entire table at once will beat up your DB, the DB host, the network, the host your code runs on, and your Rails server and app.
7

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?}

1 Comment

This seems to always return @apps.count whether its true or false. For example, @apps.count{|app| false} == @apps.count{|app| true}
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.