Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby idiomatic way to return a boolean

Tags:

ruby

Is there a more idiomatic way for me to return a boolean in #survey_completed? This is how I did things in C#, and I have always felt that the last ternary clause to return false was redundant, so perhaps Ruby has a better way of doing this?

This is how what my code currently looks like:

  def survey_completed?
    self.survey_completed_at ? true: false
  end

  def survey_completed_at
    # Seeing as the survey is submitted all or nothing, the time the last response is persisted
    # is when the survey is completed
    last_response = self.responses.last
    if last_response
      last_response.created_at
    end
  end
like image 380
Lee Avatar asked Jan 13 '23 15:01

Lee


2 Answers

You can use double negation:

def survey_completed?
  !!survey_completed_at
end
like image 78
Marek Lipka Avatar answered Jan 24 '23 14:01

Marek Lipka


  def survey_completed?
    !survey_completed_at.nil?
  end
like image 30
Santhosh Avatar answered Jan 24 '23 14:01

Santhosh