Simplify the 'defined?' API (#3)

Submitted by: Wilson Bilkovich

This revision by: Wilson Bilkovich

Date: Wed Jan 03 16:11:26 -0500 2007

View earlier revisions

ABSTRACT

Problem: Based on a quick count, there are 26 possible return values from the defined? keyword. This adds unnecessary complexity to the API.

Solution: Change ‘defined?’ to return true or false, rather than a string or nil.

PROBLEM

After examining every usage of ‘defined?’ in Core, Stdlib, and all the gems I have installed (including Rails), these 26 return values are never used in any role other than ‘true’ or ‘false’.

This additional information goes unused, but represents a significant burden for Ruby implementors.

The necessary code changes are straightforward, and I will happily provide a patch.

A rough estimate is that this version of the ‘defined?’ API could be implemented with 30 or 40% of the code that the existing version requires. Some of the return values of ‘defined?’ make distinctions that are not normally exposed in Ruby programs, such as local variables vs. local variables in blocks as separate concepts.

PROPOSAL

Currently:

defined? self # => ‘self’

defined? super # => ‘super’ or nil

defined? super(x,y,z) # => ‘super’ or nil

defined? nil # => ‘nil’ (string, not nil itself)

defined?(x = 5) # => ‘assignment’

defined?($0) # => ‘global-variable’

defined?($1) # => nil

“foo” =~ /(o)/

defined?($1) # => ”$1”

defined?(foo.some_accessor = 5) # => ‘assignment’

etc, etc, etc

Proposed: All of the above examples that return strings would return true, and any that return nil would return false.

ANALYSIS

This requires a language-level change because “defined?” is not a method call. It is a node type in the Ruby grammar, rather than being a method on Kernel or Object.

IMPLEMENTATION

If there is interest, I can produce a patch for “is_defined” in eval.c.

Comments

from Roger Deloy Pack, Wed Oct 17 09:48:04 -0400 2007

A small query on the ruby mailing list didn't seem to reveal any body using
defined? for more than true/nil.

A small query on the ruby mailing list didn&#39;t seem to reveal any body using defined? for more than true/nil.<br><br>



Return to top

Copyright © 2006, Ruby Power and Light, LLC