帮助重构这个讨厌的 Ruby if/else 语句 [英] Help refactoring this nasty Ruby if/else statement

查看:36
本文介绍了帮助重构这个讨厌的 Ruby if/else 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个大而多毛的 if/else 语句.我向它传递一个跟踪号,然后它确定它是什么类型的跟踪号.

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? Specifically wanting to reduce the number of lines of codes.

if num_length < 8
  tracking_service = false
else
  if number[1, 1] == 'Z'
    tracking_service = 'ups'
  elsif number[0, 1] == 'Q'
    tracking_service = 'dhl'
  elsif number[0, 2] == '96' && num_length == 22
    tracking_service = 'fedex'
  elsif number[0, 1] == 'H' && num_length == 11
    tracking_service = 'ups'
  elsif number[0, 1] == 'K' && num_length == 11
    tracking_service = 'ups'
  elsif num_length == 18 || num_length == 20
    check_response(number)
  else
    case num_length
    when 17
      tracking_service = 'dhlgm'
    when 13,20,22,30
      tracking_service = 'usps'
    when 12,15,19
      tracking_service = 'fedex'
    when 10,11
      tracking_service = 'dhl'
    else
      tracking_service = false  
    end  
  end
end

是的,我知道.真恶心.

Yes, I know. It's nasty.

推荐答案

试试这个.我使用 case 和正则表达式重写了它.我还使用 :symbols 而不是 "strings" 作为返回值,但您可以将其改回来.

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

这篇关于帮助重构这个讨厌的 Ruby if/else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆