aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authordrbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2013-01-19 00:52:57 +0000
committerdrbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2013-01-19 00:52:57 +0000
commitb7ae472b58f0bb47754b0db975fe74359c2d4b0f (patch)
tree1fa64a1cc17a29351428b04ab023172a051d7e98
parent1ecaf599ff22d6102dde5b76699d78ec13758d88 (diff)
downloadruby-b7ae472b58f0bb47754b0db975fe74359c2d4b0f.tar.gz
* doc/syntax/miscellaneous.rdoc: Added section on defined?
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38882 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r--ChangeLog4
-rw-r--r--doc/syntax/miscellaneous.rdoc30
2 files changed, 34 insertions, 0 deletions
diff --git a/ChangeLog b/ChangeLog
index cebd18faa4..db144d6f5f 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,7 @@
+Sat Jan 19 09:52:46 2013 Eric Hodel <drbrain@segment7.net>
+
+ * doc/syntax/miscellaneous.rdoc: Added section on defined?
+
Sat Jan 19 09:27:31 2013 Eric Hodel <drbrain@segment7.net>
* doc/syntax/assignment.rdoc (Local Variables and Methods): Made it
diff --git a/doc/syntax/miscellaneous.rdoc b/doc/syntax/miscellaneous.rdoc
index cb5865ff01..8f424f019f 100644
--- a/doc/syntax/miscellaneous.rdoc
+++ b/doc/syntax/miscellaneous.rdoc
@@ -53,6 +53,36 @@ You may undef multiple methods:
You may use +undef+ in any scope. See also Module#undef_method
+== +defined?+
+
++defined?+ is a keyword that returns a string describing its argument:
+
+ p defined?(UNDEFINED_CONSTANT) # prints nil
+ p defined?(RUBY_VERSION) # prints "constant"
+ p defined?(1 + 1) # prints "method"
+
+You don't need to use parenthesis with +defined?+ but they are recommended due
+to the {low precedence}[rdoc-ref:syntax/precedence.rdoc] of +defined?+.
+
+For example, if you wish to check if an instance variable exists and that the
+instance variable is zero:
+
+ defined? @instance_variable && @instance_variable.zero?
+
+This returns <code>"expression"</code> which is not what you want if the
+instance variable is not defined.
+
+ @instance_variable = 1
+ defined?(@instance_variable) && @instance_variable.zero?
+
+Adding parentheses when checking if the instance variable is defined is a
+better check. This correctly returns +nil+ when the instance variable is not
+defined and +false+ when the instance variable is not zero.
+
+Using the specific reflection methods such as instance_variable_defined? for
+instance variables or const_defined? for constants is less error prone than
+using +defined?+.
+
== +BEGIN+ and +END+
+BEGIN+ defines a block that is run before any other code in the current file.