Home > Back-end >  ruby on rails pass a value to .last()
ruby on rails pass a value to .last()

Time:03-30

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.

CodePudding user response:

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

  • Related