I am trying to calculate the average of parameters by passing them to an array but I am getting the following error. So I have doubt am I doing it right?
Here is my code
arr= #r1+#r2+#r3+#r4+#r5
#current_user_satisfaction= arr.inject{ |sum, el| sum + el }.to_i / arr.size
Where I am getting r1, r2,r3,r4 from the DB.
I am getting the following error
: syntax error, unexpected tIDENTIFIER, expecting keyword_end #current_user satisfaction= arr.inject{ |sum, el| sum +... ^
What was my problem where is my error. I actually started learning ROR very recently.
This what I am writing to do
I have as set of variables which I am taking from db based up user_id and company_id
the variables are
#r1=company_rating.collect(&:r1)
#r2=company_rating.collect(&:r2)
#r3=company_rating.collect(&:r3)
#r4=company_rating.collect(&:r4)
And I wanted to find the avg of all those variables.
So I am doing it like arr = [#r1,#r2,#r3,®r4]
#current-user_satisfaction= arr.sum.compact /arr.size
But I am getting an error / is undefined and Why I am doing compact is because I have sum of the nil values in that
So please help how do this.
This is not an array!
arr= #r1+#r2+#r3+#r4+#r5
This is a sum. Should be arr= [#r1,#r2,#r3,#r4,#r5]
Additionally you missed dot between #current_user and satisfaction.
Also it is not as it should be done in rails. Could you show us how those variables are set?
First, You need to create the array like this
arr= [#r1,#r2,#r3,#r4,#r5]
The error you are getting is about the . dot you missed between #current_user and satisfaction. Change it accordingly and you will get it working.
As far as I think, you don't need an array there. if you are doing, arr= #r1+#r2+#r3+#r4+#r5, it is already calculating the sum of values, why you need to put them to array and go for a loop.
However, If you still want to use array, instead of arr.inject{ |sum, el| sum + el }, you can use arr.reduce('+'), which does the same thing of calculating sum of all array values. This has nothing to do with your problem, but makes your code more understandable.
Related
I'm pretty new to ruby on rails, so I'm probably missing some syntax. Big picture I am trying to get the value for a specified percentile. Conceptually I am taking my table 'Scores', sorting it, getting the last 'x' values, and then taking the first value. I can't seem to figure out how to pass 'x', which is based on the length of the dataset to the chain.
def get_percentile()
record_count = Scores.count(:id)*0.05
record_threshold = record_count.round()
Score_percentile = Scores.order(:points).last(record_threshold).first().points
return Score_percentile
end
get_percentile
If I just enter .last(20) this works as I expect, so I just don't know how to pass the variable.
Thanks.
You may be passing a 0 into your .last() function with your rounding.
There are a variety of options to make sure you pass at least a 1
[record_threshold, 1].max will give you at least 1. https://apidock.com/ruby/Enumerable/max
Changing .round() to .ceil() rounds up in all instances. https://apidock.com/ruby/Float/ceil
Hi I'm working on a project and I have to get the sum of an attribute of a active record collection. So I used:
#total = #records.sum(:cost)
However this gives the wrong value, for example if I have:
#records.each{ |x| puts x.cost}
I get 118.80 and 108.00
but for #total I get 680.40, which obviously isn't the answer, however if I use:
#total = 0
#records.each{ |x| #total = #total + x.cost}
I get the right answer of 226.80
If anyone can help me understand what is going on here it would be greatly appreciated.
Be careful, as a record collection is an instance of ActiveRecord::Associations::CollectionProxy, not an Array. It means that if you call:
#object.collection.sum(:cost)
actually what gets called is this method: http://apidock.com/rails/v4.2.7/ActiveRecord/Calculations/sum
And it will call sum in the SQL database, so the result gets influenced by the parameters of the query, e.g. groups, joins, etc.
While if you want to use Array sum, as in here: http://apidock.com/rails/Enumerable/sum
You would have to make your object Array first, via to_a:
#object.collection.to_a.sum(&:cost)
try this:
pluck the values of attr cost into an array and aggregate their sum
#total = #records.pluck(:cost).sum
I have the following hash, #example_set that I want to get and store data from.
{"Example1"=>{:campaign=>"Example1", :impressions=>12, :conversions=>1, :clicks=>14,
"Example2"=>{:campaign=>"Example2", :impressions=>4042, :conversions=>2, :clicks=>11}}
I want to do the following to combine the total conversions but am running into a TypeError: no implicit conversion of Symbol into Integer.
#totals = 0
#example_set.each do |report|
#totals += report[:conversions]
end
Ideally this would set #totals to 3
I am new to rails so any additional detail and instruction would be much appreciated (especially if there is a better way to do this.. which I assume there is)
You want to iterate over values of that map, I think.
#example_set.values.each
Hi I am find the average
This what I am trying to do
I have as set of variables which I am taking from db based upon user_id and company_id the variables are And I cannot added then and there because I need to display individual parameter in my show page and I also wanted to display their average
So I am trying to do as below
#r1=company_rating.collect(&:r1)
#r2=company_rating.collect(&:r2)
#r3=company_rating.collect(&:r3)
#r4=company_rating.collect(&:r4)
So I am doing it like
arr = [#r1,#r2,#r3,®r4]
#totalaverage= arr.sum.compact /arr.size
My array sample looks like [10,20,30,nil],[nil,nil,nil,nil],[30,40,50,60]
And If I have array all Nil then it should show be Nil
But I am getting an error undefined method `/' for # and Why I am doing compact is because I have sum of the nil values in that
So please help how do this.
First of all, you define arr as an array of arrays. #r1, #r2 etc. are all arrays and what [#r1, #r2, ...] does is just mixing them up in another array. You probably want to merge them, not include them in another array:
arr = #r1 + #r2 + #r3 + #r4
Second, you should call arr.compact first, then sum the contents up. Also, I'm not really sure about the sum method. I'd use reduce(&:+) instead. So, to answer your question, '/' fails because compact returns an Array, and you're trying to divide an Array to a number. This looks better:
arr = #r1 + #r2 + #r3 + #r4
#totalaverage = arr.compact.reduce(&:+) / arr.size
What Array#reduce(&:+) does is to apply the + operator between array members and return the value (not an array).
EDIT: arr.sum does work if you're using Ruby on Rails. Otherwise use arr.reduce(&:+) instead.
Do as below,which should work :
#totalaverage= arr.flat_map(&:compact).inject(:+) /arr.size.to_f
Actually #totalaverage is an array of array. Where each internal element(array) of #totalaverage can have nil values also(as you shown). So you need to remove those nil entries if any from the internal array of #totalaverage. And arr.map(&:compact) will do the same job.
Simplest way to do this if you're using Rails:
#totalaverage = a.flatten.compact.sum.to_f / a.flatten.compact.size if a.flatten.compact.present?
This will assign to #totalaverage the result or nil in case all the values are nil.
my app has invoices and invoice_items. Each invoice has many invoice_items.
In my invoice_items model, I have a calculation to work out the total:
def total
#total ||= quantity.to_d * price
end
That works fine. What I'm trying to do is calculate the sum of the totals and I'm stuck.
In the console, I've tried this:
invoice = Invoice.first
invoice.invoice_items.sum(:total)
But I get an error saying :total doesn't exist. Which I guess it doesn't.
My question is how I can go about doing this calculation?
-- UPDATE --
I've tried the following as per #paukul's answer:
invoice.invoice_items.sum(&:total)
This gives the error:
ArgumentError: wrong number of arguments (1 for 2)
Thanks
you are calling .sum on the whole invoice_items array (which obviously doesn't know the .total method) and not each individual invoice item.
To make it work you want to use the block version of sum which yields every single item in the array to the block and sums up their results.
with the symbol to proc syntactic sugar, you are almost there.
Try invoice.invoice_items.all.sum(&:total) which is equivalent to invoice.invoice_items.inject(0) { |sum, item| sum + item.total }
see the RDoc for Enumerable#sum