Ruby:使用块初始化Object实例

时间:2015-12-23 10:45:00

标签: ruby

是否可以初始化Object实例,对其执行操作并返回此实例而不创建临时变量?

例如:

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 

而不是:

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

1 个答案:

答案 0 :(得分:4)

您可以使用tap

  

向块发出自我,然后返回自己。

示例:

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

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

object.foo
#=> "foo"