Reputation: 1275
I have a Users table that I want to analyze by counting the number of cells that have data like COUNTA function of Excel, which counts the cells that have data:
JOB | ADDRESS | LOOKS | WEALTH
Matthew Tax Collector | | 3 | 9
Mark | Galilee | 6 |
socio_count counts the cells that have data in address and job. personality_count counts the cells that have content in looks, wealth. Is there an easier way to do this in Rails? (because there are much more columns).
In Excel it would be
COUNTA(B2:C2) # outputs 1
COUNTA(D2:E2) # outputs 2
My Rails code is:
socio_count = 0
if @user.job.present?
socio_count = socio_count + 1
end
if @user.address.present?
socio_count = socio_count + 1
end
# more columns here..
@socio_count = socio_count # outputs 1
personality_count = 0
if @user.looks.present?
personality_count = personality_count + 1
end
if @user.wealth.present?
personality_count = personality_count + 1
end
# more columns here..
@personality_count = personality_count # outputs 2
Upvotes: 0
Views: 30
Reputation: 5343
Use .send
.
%i(job address phone).each do |symbol|
@user.send(symbol).present? and socio_count += 1
end
That's a bit more DRY. There are also ways to access an ActiveRecord column by name. And you should edit your post to explain Excel's COUNTA, for those who don't know it...
Upvotes: 2