Ruby, value bucketing, beautify code

前端 未结 5 642
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 02:04

So I have this code:

def self.age_to_bucket(age)
  age = age.to_i

  if age >= 0 && age <= 12
    1
  elsif age >= 13 && age <= 17
          


        
5条回答
  •  无人共我
    2021-01-25 02:43

    Just for fun (this is not the efficient way, but for small arrays is just fine):

    ranges = [0, 13, 18, 25, 30, 35, 40, 50, 65, Float::INFINITY].each_cons(2).map { |a, b| (a..b) }
    n = ranges.map.with_index { |range, idx| idx if range.include?(15) }.compact.first + 1 
    #=> 2
    

    Note that if the intervals were dynamic you'd have to implement it in a similar fashion.

提交回复
热议问题