echo if variable is defined in ruby/erb

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}" %>

defined? is the ruby equivalent to isset().

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

Tags:

Ruby

Erb