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.)
You can define the increment as so
(0..10).step(0.5)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With