15

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

Community
  • 1
  • 1
tester
  • 22,441
  • 25
  • 88
  • 128

2 Answers2

28

defined? is the ruby equivalent to isset().

<%= defined?(a) ? a : 'some default' %>
Gilad Peleg
  • 2,010
  • 16
  • 29
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
13

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}" %>
Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
  • `<%= a if defined? a %>` is great! thank you! – tester Oct 15 '12 at 23:48
  • `nil?` wouldn't be safe, correct? – tester Oct 15 '12 at 23:49
  • you can't test `a.nil?` if it's not defined, it'll crash. Use `defined?` to do it. You can however assign `nil` to `a` in my second example above as long as you just try to output it. If you want to call methods on it though, it'll crash ... ! – Anthony Alberto Oct 15 '12 at 23:56
  • 1
    Also I recommend using `irb` a lot to experiment and see what you can and cannot do with the language. It's a powerful tool every rubyist uses, even the experienced ones! – Anthony Alberto Oct 15 '12 at 23:58