Help refactoring this nasty Ruby if/else statement

前端 未结 5 1769
无人共我
无人共我 2021-02-02 01:57

So I have this big, hairy if/else statement. I pass a tracking number to it, and then it determines what type of tracking number it is.

How can I simplify this thing? Sp

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 02:41

    Try this. I rewrote it using case and regular expressions. I also used :symbols instead of "strings" for the return values, but you can change that back.

    tracking_service = case number
      when /^.Z/ then :ups
      when /^Q/ then :dhl
      when /^96.{20}$/ then :fedex
      when /^[HK].{10}$/ then :ups
    else
      check_response(number) if num_length == 18 || num_length == 20
      case num_length
        when 17 then :dhlgm
        when 13, 20, 22, 30 then :usps
        when 12, 15, 19 then :fedex
        when 10, 11 then :dhl
        else false
      end
    end
    

提交回复
热议问题