Skip to main content

How do I check if runner.interest is not null in this interpolation?

Rails • Asked by Neil Patel

hi

i am working on this interpolation where the runners has interests but lets say the runner has not interests , or has not entered any interests how would we interpolate this

Your runner is called #{@runner.first_name.capitalize}. #{@runner.first_name.capitalize}’s first run to you will be on #{format_date(@pairing.first_visit_date)} at #{@pairing.usual_visit_time}. #{@runner.first_name.capitalize}   #{@runner.first_name.capitalize} likes #{@runner.interests.squish}

    is something like if @runner.interests.squish.nil? = "no interests"

Hey Neil,

Any reason you can't just do a if ?

if @runner.interests.squish.nil? 
  "#{@runner.first_name.capitalize} has no interests"
else
 "Your runner is called #{@runner.first_name.capitalize}. #{@runner.first_name.capitalize}’s first run to you will be on #{format_date(@pairing.first_visit_date)} at #{@pairing.usual_visit_time}. #{@runner.first_name.capitalize}   #{@runner.first_name.capitalize} likes #{@runner.interests.squish}"
end


Ah sweet, glad that was it! Anytime! :)


It can also be refactored as well , so it uses less code
by using the if/else statement in the interpolation

. #{@runner.first_name.capitalize} likes #{@runner.interests.present? ? @runner.interests.squish : 'running and voluntering'}


Yep, you're correct! That is called the ternary operator

Just be aware that short code is not an absolute goal - clarity is always better than brevity - and in this case I'd argue that the ternary method isn't clear enough since it can be hard to see the ? and : in the operator, so for the sake of my fellow programmers that come after me (and myself a few months down the road), I'd go with the long form.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.