Save 36% for Black Friday! Learn more

Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Neil Patel asked in Rails

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"
Reply

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
Reply

thanks Jacob!

Reply

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

Reply

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'}

Reply

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.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.