Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Compare: Ruby Keyword: defined?

Showing with 21 additions and 5 deletions.
  1. +21 −5 Ruby Keyword: defined?.md
26 Ruby Keyword: defined?.md
View
@@ -2,12 +2,28 @@
defined? self ⇒ "self"
defined? true ⇒ "true"
defined? false ⇒ "false"
- # ____ ⇒ "expression"
+ defined? "asdf" ⇒ "expression"
+ defined? a = 3 ⇒ "assignment" # but doesn't actually set a to 3.
defined? printf ⇒ "method"
printf = 3
- defined? printf ⇒ "local-variable"
- defined? a = 3 ⇒ "assignment" # but doesn't actually set a to 3.
+ defined? printf ⇒ "local-variable" # nil if there is no local or method with that name
+ defined? $foo ⇒ "global-variable" # nil if $foo has not been assigned to
+ defined? Object ⇒ "constant" # nil if there is no constant with that name
+ defined? super ⇒ "super" # nil if there is no super method.
+ defined? yield ⇒ "yield" # nil if no block was passed to this method
+
+defined? is most often used to determine whether a constant or global variable is defined. For example ruby-1.8.7 didn't have a RUBY_ENGINE constant, so jruby was often detected using:
+
+ defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
+
+Another idiomatic use is to safely call a super-method:
+
+ super if defined?(super)
+
+It can be used to detect whether a block was passed to this method, though `block_given?` is usually preferred.
+
+ yield if defined?(yield)
-What the heck is this thing good for?
+Although the return value of `defined?` is a string, this is usually ignored and only the truthiness of the result considered.
-Please answer at: https://github.com/rking/pry-docmore/wiki
+Improve these docs at https://github.com/rking/pry-docmore/wiki
Something went wrong with that request. Please try again.