我正在尝试减少以下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
语句,因此希望将其缩小一点,以免它变得太笨重。有一个相对不错的代码重复量,所以试图弄清楚如何重构它。
答案 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