Submitted by: Wilson Bilkovich
This revision by: Wilson Bilkovich
Date: Wed Jan 03 16:11:26 -0500 2007
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.
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.
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.
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.
If there is interest, I can produce a patch for “is_defined” in eval.c.
Copyright © 2006, Ruby Power and Light, LLC
Comments
from Roger Deloy Pack, Wed Oct 17 09:48:04 -0400 2007