Class: Object

Inherits:
BasicObject
Defined in:
lib/rubyexts/try.rb,
lib/rubyexts/object.rb,
lib/rubyexts/try_dup.rb

Instance Method Summary collapse

Instance Method Details

#define_instance_method(*args) {|block| ... } ⇒ Object

Defines a instance method on class of the object.

Examples:

class Experiment
  def method_generator
    define_instance_method(:new_method) do |arg|
      puts "Method :new_method called with #{arg}"
    end
  end
end
Experiment.new.methods.include?(:new_method) # => false
Experiment.new.method_generator
Experiment.new.methods.include?(:new_method) # => true

Parameters:

  • Method (Symbol)

    name

  • +Method+ (Method, Proc, optional)

    or Proc which will be used as body of the method

Yields:

  • (block)

    Block which will be used as body of the method

Returns:

  • (Object)

    First (and only) item of the array

See Also:

  • for define method on singleton class

Author:

  • Botanicus

Since:

  • 0.0.3



33
34
35
# File 'lib/rubyexts/object.rb', line 33

def define_instance_method(*args, &block)
  self.class.send(:define_method, *args, &block)
end

#not_nil?true, false

The opposite of #nil?.

Returns:

  • (true, false)

    True if self is nil, false otherwise

Author:

  • Botanicus

Since:

  • 0.0.3



9
10
11
# File 'lib/rubyexts/object.rb', line 9

def not_nil?
  not self.nil?
end

#try(method, *args) {|block, optional| ... } ⇒ Object?

Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.

Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does.

Examples:

@post.try(:name) # instead @post && @post.name
eBook.try(:find, 1)
@post.try(:collect) { |p| p.name }

Parameters:

  • Method (Symbol)

    which will be called on object if object respond to this method

  • Arguments (Object, optional)

    for method argument

Yields:

  • (block, optional)

    Block for method argument

Returns:

  • (Object, nil)

    Return value of object.send(method) if object respond to method or nil

Author:

  • Botanicus

Since:

  • 0.0.3



20
21
22
# File 'lib/rubyexts/try.rb', line 20

def try(method, *args, &block)
  self.send(method, *args, &block) if self.respond_to?(method)
end

#try_dupObject



22
23
24
# File 'lib/rubyexts/try_dup.rb', line 22

def try_dup
  self.dup
end