我正在编写一些代码,结果却让我觉得太难看了。反正我是否可以重构它以便我不使用嵌套的if语句?
def hours_occupied(date)
#assuming date is a valid date object
availability = get_work_hours(date)
focus = "work"
if availability.nil
availability = get_family_hours(date)
focus = "family"
if availability.nil
availability = get_friend_hours(date)
focus = "friends"
end
end
end
我知道我可以做这样的事情以获得可用性
availability = get_work_hours(date) || get_family_hours(date) || get_friend_hours(date)
但是如何相应地设置焦点变量?
答案 0 :(得分:5)
我会做类似以下的事情,因为它清楚地表明每个案例是互斥的:
def hours_occupied(date)
if availability = get_work_hours(date)
focus = "work"
elsif availability = get_family_hours(date)
focus = "family"
elsif availability = get_friend_hours(date)
focus = "friends"
end
end
答案 1 :(得分:3)
我写道:
def hours_occupied(date)
focus = if (availability = get_work_hours(date))
"work"
elsif (availability = get_family_hours(date))
"family"
elsif (availability = get_friend_hours(date))
"friends"
end
# I guess there is more code here that uses availability and focus.
end
但是,我不确定为不同类型设置不同的方法是一个好主意,它会使代码更难编写。使用Enumerable#map_detect的另一种方法:
focus, availability = [:work, :family, :friends].map_detect do |type|
availability = get_hours(date, type)
availability ? [type, availability] : nil
end
答案 2 :(得分:1)
的情况也是一个选项:
focus = case availability
when get_work_hours(date)
"work"
when get_family_hours(date)
"family"
when get_friend_hours(date)
"friends"
end
答案 3 :(得分:1)
另一种方法是在需要时重新分配值:
def hours_occupied(date)
availability, focus = get_work_hours(date), "work"
availability, focus = get_family_hours(date), "family" unless availability
availability, focus = get_friend_hours(date), "friend" unless availability
end
或使用迭代器:
def hours_occupied(date)
availability = focus = nil
%w(work family friend).each {|type| availability, focus = self.send(:"get_#{type}_hours", date), type unless availability}
end