0

I want to know if there is a way to output a string only if the value isn't nil but to it without repeating the item.

In other words I want to do the following:

<%= MyClass.thing.stuff.more_stuff if !MyClass.thing.stuff.more_stuff.blank? %>

But without having to repeat the whole thing twice. Not even sure if it's possible but I couldn't figure out the right terms to Google.

1
  • 2
    If MyClass.thing.stuff.more_stuff is nil so that <%= MyClass.thing.stuff.more_stuff %> will returns nil too. And as result it won't print any output in your view. Commented Apr 24, 2015 at 0:36

1 Answer 1

1
<%= MyClass.thing.stuff.more_stuff %>

will work. Because an outputted nil will turn into an empty string and thus no output in an erb template.

So will presence if you want something more complicated

<%= MyClass.thing.stuff.more_stuff.presence %>

Docs: http://apidock.com/rails/Object/presence

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.