Topic: Cleaning up Ugly IF-Else statements

Hi All,

I'm doing multiple If statements in my Model which looks pretty ugly. I believe
this can be done in a much cleaner way.

      if self.lesson_type == "Lesson (60min) "
         self.lesson_type = "Lesson " + lesson_number
         self.lesson_comments = "60 minutes"
      end
      if self.lesson_type == "Lesson (90min) "
         self.lesson_type = "Lesson " + lesson_number
         self.lesson_comments = "90 minutes"
      end
      if self.lesson_type == "Lesson (120min) "
         self.lesson_type = "Lesson " + lesson_number
         self.lesson_comments = "120 minutes"
      end
     else
        self.lesson_type = self.lesson_type << lesson_number
     end

Any help / insight is appreciated

Thanks,

John

Re: Cleaning up Ugly IF-Else statements

Well, you could just get rid of the if statements using a case statement, but you have more repetition. Here's one way to solve it (untested):

if self.lesson_type =~ /^Lesson \(\d+min\)/
  minutes_long = self.lesson_type.match(/^Lesson \((\d+)min\)/)[1]
  self.lesson_type = "Lesson " + lesson_number
  self.lesson_comments = "#{minutes_long} minutes"
else
  self.lesson_type = self.lesson_type << lesson_number
end

I used regular expressions, but that should accept _any_ number of minutes.

Re: Cleaning up Ugly IF-Else statements

Manitoba,

Thanks, it works great!!