New Discussion

Notifications

You’re not receiving notifications from this thread.

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

5
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

thanks Jacob!

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
Create an account Log in

Learning Ruby on Rails? Join our newsletter.

We won't send you spam. Unsubscribe at any time.