Class | Object |
In: |
lib/extensions/enumerable.rb
lib/extensions/object.rb |
Parent: | Object |
Defines a singleton method on the object. For example, the following are equivalent (assume o = Object.new):
def o.add(x, y) x + y end o.define_method(:add) do |x, y| x + y end
The difference is that with define_method, you can use variables local to the current scope.
x = 5 o.define_method(:add_x) do |n| x + n end o.add_x(11) # -> 16
You can‘t define such a method as add_x above with def o.add_x; x + n; end, as def introduces a new scope.
There are three ways to provide the body of the method: with a block (as in both examples above), or with a Proc or Method object. See the built-in method Module#define_method for details.
(This method is exactly equivalent to calling Module#define_method in the scope of the singleton class of the object.)
# File lib/extensions/object.rb, line 156 def define_method(*args, &block) singleton_class = class << self; self; end singleton_class.module_eval do define_method(*args, &block) end end
Test this object for inclusion in a given collection.
45.in? (1...100) => true
This method is contained in object.rb and enumerable.rb, because it logically belongs in both.
# File lib/extensions/object.rb, line 47 def in?(enumerable) enumerable.include?(self) end
The opposite of nil?.
"hello".non_nil? # -> true nil.non_nil? # -> false
# File lib/extensions/object.rb, line 84 def non_nil? not self.nil? end
The opposite of nil?.
"hello".not_nil? # -> true nil.not_nil? # -> false
# File lib/extensions/object.rb, line 66 def not_nil? not self.nil? end
Returns a pretty-printed string of the object. Requires libraries pp and stringio from the Ruby standard library.
The following code pretty-prints an object (much like p plain-prints an object):
pp object
The following code captures the pretty-printing in str instead of sending it to STDOUT.
str = object.pp_s
# File lib/extensions/object.rb, line 112 def pp_s pps = StringIO.new PP.pp(self, pps) pps.string end