if defined? “what does it mean?!”
Plowing through various Rails and Ruby source code, I keep running across the method defined?. However, a quick look though the API turned up nothing on it. Where’s it coming from? I can’t find it in Module, Kernel, or Object…time to explore! A quick Google search shows
As it turns out defined? lives in eval.c. The logic responsible for defined? actually has the identity is_defined starting around line 2249. As Redhanded explains: “defined? takes its argument and simply queries the symbol table to see if it is defined. If it is, you get a simple string of identification”:
$ x = 10 => 10 $ defined? x => "local-variable" $ def hello; puts "Hello" end $ defined? hello => "method" $ class Test; end $ defined? Test =>"constant"
Examples of use
Since I haven’t had the opportunity to use it yet, Here’s a couple examples I’ve found:
In Rails initializer.rb uses it to test for the existence of a constant:
def initialize_logger return if defined?(RAILS_DEFAULT_LOGGER)
The method real_connect in mysql.rb uses it to check UNIXSocket:
if (host == nil or host == "localhost") and defined? UNIXSocket then ...
Cliff notes version
- defined? is classified as an operator not a method
- defined? returns nil if the argument passed to it is NOT defined
- defined? returns a string identification of the argument passed as defined in the symbol table
Now, I wonder where and how the method is_defined is translated into the operator defined?