可以使用大量字符串扫描重构这个if / else语句吗?

时间:2013-08-21 13:45:52

标签: ruby if-statement refactoring

我正在尝试减少以下if / else语句......

event_description = "We have a record of item FJ750701138GB as being delivered from Northampton North DO on 2013-08-10."
time = Time.now.strftime("%H:%M")

if date = event_description.scan(/We have a record of item [^>]* as being delivered from [^>]* on ([^<]*)./i).join
  datetime = Date.strptime("#{date} #{time}","%Y-%m-%d %H:%M").to_time
elsif date = event_description.scan(/Your item with reference [^>]* was delivered from our [^>]* Delivery Office on ([^<]*) ./i).join
  datetime = Date.strptime("#{date} #{time}","%d/%m/%y %H:%M").to_time
elsif date = event_description.scan(/Item [^>]* was collected and signed for by the addressee on the ([^<]*) from [^>]*/i).join
  datetime = Date.strptime("#{date} #{time}","%Y-%m-%d %H:%M").to_time
elsif date = event_description.scan(/Your item, posted on [^>]* with reference [^>]* was delivered in [^>]* on ([^<]*)./i).join
  datetime = Date.strptime("#{date} #{time}","%d/%m/%y %H:%M").to_time
end

event.occurred_at = datetime

这个的主要功能是扫描各种字符串,从中提取日期,并创建一个Date对象。

  • 日期可以采用不同的格式(您可以在striptime个实例中看到)
  • 随着时间的推移,我们会在扩展我们正在扫描的字符串时添加更多elsif语句,因此希望将其缩小一点,以免它变得太笨重。

有一个相对不错的代码重复量,所以试图弄清楚如何重构它。

2 个答案:

答案 0 :(得分:1)

我认为最好的选择是解析所需的日期和时间格式。

像这样。

case description
when /(\d{4})-(\d{2})-(\d{2})/
  puts year  = $1
  puts month = $2
  puts day   = $3
when /(\d{2})\/(\d{2})\/(\d{2})/
  puts day   = $1
  puts month = $2
  puts year  = $3
else
  puts "Unknown Date/Time"
end

然后使用变量转换为您的时间。

答案 1 :(得分:0)

String#scan将返回一个数组,对结果执行join会得到一个字符串,因此代码中的第一个条件将始终满足

如果这是有目的的,您可以删除其他条件,您的代码可以重构为:

event_description = "We have a record of item FJ750701138GB as being delivered from Northampton North DO on 2013-08-10."
date = event_description.scan(/We have a record of item [^>]* as being delivered from [^>]* on ([^<]*)./i).join
time = Time.now.strftime("%H:%M")
datetime = Date.strptime("#{date} #{time}","%Y-%m-%d %H:%M").to_time
event.occurred_at = datetime