echo if variable is defined in ruby/erb

tester picture tester · Oct 16, 2012 · Viewed 18.9k times · Source

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

Answer

Alex Wayne picture Alex Wayne · Oct 16, 2012

defined? is the ruby equivalent to isset().

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