Search code examples
ruby-on-railsrubyruby-on-rails-4ruby-2.0short-circuiting

Short circuit evaluation in ruby / rails with defined?


Looking to have two tests on a variable, that might not be defined in a rails view.

<% if defined(:var) && var.present? %>
    <%= var.value %>
<% end %>

However, this is throwing a undefined local variable or method error when var is not defined. I assumed ruby/rails would short circuit the first expression and not try to evaluate the second, similar to python

>>> a = False
>>> a and b
False
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

Any reason why short circuit is preceeding to the second evaluation?


Solution

  • I think you want this:

    if defined?(var) && var.present?
    

    :var will always be defined as it's a symbol.

    > defined?(:var)
    => "expression"
    > defined?(var)
    => nil
    > var = 1
    => 1
    > defined?(var)
    => "local-variable"