开发者

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

开发者 https://www.devze.com 2023-03-02 00:31 出处:网络
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...

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消