2013-11-26 31 views
3

元编程Ruby第3章有一个任务来编写C#的using statement的Ruby等价物。我开始了:Ruby的使用方法是什么?

class Resource 
    def dispose 
    @disposed = true 
    end 
    def disposed? 
    @disposed 
    end 
end 
def using(r) 
    puts "Not implemented." 
end 

r = Resource.new 
using(r) 

我还没有执行using呢。然而,当我运行这段代码,我得到

in `using': wrong argument type Resource (expected Module) (TypeError) 

而且,如果我喜欢写东西using(Kernel)using(Enumerable)等,在程序完成没有错误。据我所知,在Ruby中没有using方法或关键字,但我也在pry和irb中获得相同的行为。发生什么事?

+1

我得到“未实现。”当我运行上面的代码时,为我工作的方式应该是1.9.3 – hirolau

+0

您运行的是什么ruby版本?在后面的MRI版本中不应该有一种叫'使用'的方法 – phoet

+2

你可以看到[here](http://www.ruby-doc.org/core-2.0.0/doc/syntax/refinements_rdoc.html),当我们需要使用'using'方法.'''将模块名称作为参数,而不是对象。你得到了错误,当你通过'Resource'的实例时,'使用'用于激活细化。请参阅此博客['Refining Ruby'](http://blog.headius.com/2012/11/refining-ruby.html) –

回答

1

如果你想要做的是,在红宝石2.1则需要修补main对象,因为它已经有方法就像在评论中提到的真实:

self.instance_eval do 
    def using(r) 
    puts "Not implemented." 
    end 
end 
+0

谢谢。我使用2.1。 –

+0

[Documentation](http://ruby-doc.org/core-2.1.0/Module.html#method-i-using) –

1

在评论中指出有不应该是一个using方法。尝试运行method(:using).owner以查看是否获得更多信息。 irb上的预期结果是

"NameError: undefined method `using' for class `Object'" 

但您应该获得您使用的来源。

相关问题