Ruby: nested if statements

I wrote the code, and it turned out to be too ugly to my liking. Is there anyway that I can reorganize it so that I do not use nested if statements?

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 

I know that I can do something similar for accessibility

 availability = get_work_hours(date) || get_family_hours(date) || get_friend_hours(date) 

but how to set the focus variable accordingly?

+4
source share
4 answers

Another way is to reassign the values ​​if necessary:

 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 

or using an iterator:

 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 
+1
source

I would like to do something like the following, as it makes it clear that each case is mutually exclusive:

 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 
+5
source

I would write:

 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 

However, I'm not sure that great methods for different types are a good idea, it makes the code harder to write. Another approach using Enumerated # map_detect :

 focus, availability = [:work, :family, :friends].map_detect do |type| availability = get_hours(date, type) availability ? [type, availability] : nil end 
+3
source

A , when also an option:

 focus = case availability when get_work_hours(date) "work" when get_family_hours(date) "family" when get_friend_hours(date) "friends" end 
+1
source

Source: https://habr.com/ru/post/1487065/


All Articles