mikeymurph77
mikeymurph77

Reputation: 802

Using defined? in a Ternary operator

I'm trying to clean up my code from this...

<% if defined? foo == "local-variable" %>
    <% foo = foo %>
<% else %>
    <% foo = nil %>
<% end %>

To use a ternary operator like so...

<% defined? foo == "local-variable" ? foo : nil %>

However the ternary does not run properly and defaults to the nil ... I'm rather new to using ternary operators (may have gotten into the habit of using them since they save lines)... is using defined? in a ternary possible?

Upvotes: 0

Views: 93

Answers (2)

Piotr Kruczek
Piotr Kruczek

Reputation: 2390

That's not exactly an answer to your question, but something like this may help:

foo ||= nil

Translates to:

if defined? foo
  foo || foo = nil
else
  foo = nil
end

Upvotes: 2

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

It should be:

<% defined?(foo) == "local-variable" ? foo : nil %>

From documentation:

... return value provides information about the expression.

>> defined?(foo) == "local-variable"
=> true
>> defined? foo
=> "local-variable"
>> defined? (foo == "local-variable")
=> "method"

Ruby operator precedence

Upvotes: 4

Related Questions