OneChillDude
OneChillDude

Reputation: 8006

Why does `defined?` return a string or nil?

In ruby, why would defined? return a string? Most other ruby methods ending with a ? return a boolean.

Was this a hack to support a feature request, or was there intentional misuse of ruby convention, and why?

Examples:

defined?(super)
=> "super"

defined?(nil)
=> "nil"

defined?(Object)
=> "constant"

Upvotes: 1

Views: 255

Answers (2)

jonahb
jonahb

Reputation: 2580

No, it was neither a hack nor a misuse of Ruby convention. As matz writes in ruby-talk 7986:

The '?' methods ... return either

  • (a) true or false
  • (b) non-false informative value or nil

defined? falls into (b).

Also, as commenters have pointed out, defined? is not a method. Matz expands in ruby-talk 1637:

[defined? is] a control structure. Not everything is a message send in Ruby, e.g. control structures, variables, blocks are not objects. defined? is among these things.

Upvotes: 7

Rots
Rots

Reputation: 5586

As sawa points out defined? is not actually a method.

If it were, the Ruby source code docs states this is allowed for methods that end in a question mark.

Methods that end with a question mark by convention return boolean. But they may not always return just true or false. Often they will may return an object to indicate a true value (or “truthy” value).

ref: https://github.com/ruby/ruby/blob/c8b3f1b470e343e7408ab5883f046b1056d94ccc/doc/syntax/methods.rdoc

Upvotes: 2

Related Questions