DreamWalker
DreamWalker

Reputation: 1387

Ruby: Initialize an Object instance with a block

Is that ever possible to initialize an Object instance, perform an operation on it and return this instance without creating a temporary variable?

For example:

def create_custom_object
  Object.new do |instance|
    instance.define_singleton_method(:foo) { 'foo' }
  end
end 
# returns an instance, but defines nothing :(
def create_custom_object
  Object.new do 
    self.define_singleton_method(:foo) { 'foo' }
  end
end
# same thing 

rather than:

def create_custom_object 
  object = Object.new
  object.define_singleton_method(:foo) { 'foo' }
  object
end 

Upvotes: 3

Views: 174

Answers (1)

Stefan
Stefan

Reputation: 114158

You could use tap:

Yields self to the block, and then returns self.

Example:

def create_custom_object
  Object.new.tap { |o| o.define_singleton_method(:foo) { 'foo' } }
end

object = create_custom_object
#=> #<Object:0x007f9beb857b48>

object.foo
#=> "foo"

Upvotes: 4

Related Questions