Ruby, value bucketing, beautify code

前端 未结 5 627
佛祖请我去吃肉
佛祖请我去吃肉 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:32

    One way is to use case

    result = case age
     when 0..12 then 1
     when 13..17 then 2
     when 18..24 then 3
     when 25..29 then 4
     -------- so on
     else 0
    end
    

    Another way would be to eliminate the redundant && in the condition.

    if age < 0 
      0
    elsif age < 13
      1
    elsif age < 18
      2
    elsif age < 25
      3
    elsif age < 30
      4
    elsif age < 35
      5
    elsif age < 40
      6
    elsif age < 50
      7
    elsif age < 65
      8
    else
      9
    

提交回复
热议问题