Help refactoring this nasty Ruby if/else statement

前端 未结 5 1768
无人共我
无人共我 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:39

    Depending on whether or not the tracking code is a ruby object, you could also put helper's in it's class definition:

    class TrackingCode < String 
      # not sure if this makes sense for your use case
      def ups?
        self[1,1] == 'Z'
      end
      def dhl?
        self[0,1] == 'Q'
      end
      def fedex?
        self.length == 22 && self[0, 2] == '96'
      end
      # etc...
    end
    

    Then your conditional becomes:

    if number.ups?
      # ...
    elsif number.dhl?
      # ...
    elseif number.fedex?
    end
    

    One simplified conditional where you are operating on the implied feature of the tracking code. Likewise, if you were to take a looping approach, your loop would also be cleaner:

    %w(ups? dhl? fedex?).each do |is_code|
      return if number.send(is_code)
    end
    

    or even:

    %w(ups? dhl? fedex?).each do |is_code|
      yield if number.send(is_code)
    end
    

提交回复
热议问题