Home » Ruby » echo if variable is defined in ruby/erb [duplicate]

echo if variable is defined in ruby/erb [duplicate]

Posted by: admin December 28, 2017 Leave a comment

Questions:

Possible Duplicate:
Checking if a variable is defined in Ruby

using Tilt’s template render method, I pass in

#... t setup ...
t.render(self, { :a => 'test', :b => 'again' })

in my template.erb

<%= a %>
<%= b %>

say I remove :b from the hash that I pass to the template. The render will fail because :b is undefined.

in PHP, I could go:

<?= isset($foo) ? $foo : '' ?>

is there any clean way (in ruby/erb) to “echo if”?

I tried <%= b.nil? ? b : '' %> but that is obviously wrong.. Any help would be appreciated

Answers:

defined? is the ruby equivalent to isset().

<% defined?(a) ? a : 'some default' %>

Questions:
Answers:

If you want to display nothing if a is not defined :

<%= a if defined?(a) %>

Also what you can do is set some default to a at the beginning of your partial if it’s not defined. This way, you’re assured that a won’t crash on you and you don’t have to test if it’s defined everywhere. I prefer this way personally.

CAUTION : if you set a to false when you pass it to the template, it’ll be reassigned to "" in my example .

<% a ||= "" %>
#Then do some things with it. No crash!
<%= a %>
<%= a*10 %>
<%= "Here's the variable a value: #{a}" %>