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

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"

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.

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.