Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Iterate numbers by decimal for a review rating field

I have a Review model which allows for a '1-10' rating system on products. In my form view, here is how I did the field to spit out a dropdown of 1-10...

<%= f.select :rating, options_for_select((0..10).to_a, @review.rating) %>

Works great, but the team is now wanting to have .5 decimal numbers for the rating system, so something can be rated 7.5, 8.0, 8.5, etc.

However, that has me stumped...how can I alter the above code and iterate through a set of numbers and increment it by .5 each time in Ruby? (Note: Yes, I have already converted my rating column from an integer to a float.)

like image 215
Shannon Avatar asked Apr 30 '11 19:04

Shannon


2 Answers

You can define the increment as so

(0..10).step(0.5)
like image 62
mark Avatar answered Sep 24 '22 14:09

mark


The answer marked as correct is not accurate. It suffers from floating point accuracy errors - you can read about this common computer science issue here: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

To increment this range accurately you should pass a BigDecimal to the step function instead of the default Ruby float:

require 'bigdecimal' 
require 'bigdecimal/util'

(0..10).step(0.5.to_d)
like image 32
zarazan Avatar answered Sep 26 '22 14:09

zarazan