Josh M.
Josh M.

Reputation: 27791

Strange && operator behavior?

Using Ruby 2.1.1 and Rails 3.2.13, I expected the following line to return true or false, but when href is nil, hasHref is set to nil:

hasHref = (defined?(href) && !href.blank?)

I know how to fix this, but was curious why this wasn't working how I expected. It worked as I had expected in Ruby 1.8.7.

Upvotes: 1

Views: 61

Answers (1)

spickermann
spickermann

Reputation: 106882

foo && bar does not return true or false. It returns foo when foo is not trueish and bar when foo was trueish. Definition of trueish: Not nil or false.

defined? never returns true or false, it returns a type description. When href is not defined then defined?(href) returns nil (what is not trueish), therefore nil is returned.

If you really need true or false change your code to:

hasHref = !!(defined?(href) && !href.blank?)

For possible return values of defined? see: http://ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html#UG

Upvotes: 4

Related Questions