3

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 

1 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.