Search code examples
ruby-on-railsruby

How can I write this conditional in fewer lines?


I wrote this code in my model:

percentage = 0
if self.date_of_birth.present?
  percentage += 15
end
if self.gender.present?
  percentage += 15
end
if self.relationship_status.present?
  percentage += 10
end
if self.language.present?
  percentage += 10
end
if self.qualification.present?
  percentage += 10
end
if self.interests.present?
  if self.interests.count >= 10
    percentage += 10
  else
    percentage += self.interests.count * 5
  end
end

But it does not look good. It is a lot of code for a small thing. I want to reduce the number of lines.


Solution

  • You can do it inline, like this:

    percentage += 15 if self.date_of_birth.present?
    

    Instead of this:

    if self.interests.count >= 10
        percentage += 10
    else
        percentage += self.interests.count*5
    end
    

    You can use a ternary operator:

    percentage += self.interests.count >= 10 ? 10 : self.interests.count*5