我想知道在没有任何方法的情况下调用对象时是否有办法返回对象而不是字符串。
例如:
class Foo
def initialize
@bar = Bar.new
end
end
有没有办法定义 Foo 类,以便发生以下情况:
foo = Foo.new
foo #returns @bar
在我感兴趣的特定情况下,我在 Rails 视图中使用演示者。演示者设置一个主要对象,然后加载一堆相关内容。重要的部分如下所示:
class ExamplePresenter
def initialize( id )
@example = Example.find( id )
end
def example
@example
end
...
end
如果我想返回 ExamplePresenter 使用的示例,我可以调用:
@presenter = ExamplePresenter.new(1)
@presenter.example
如果我也可以通过调用返回示例对象,那就太好了:
@presenter
那么,有没有办法设置一个默认方法在调用对象时返回,比如 to_s 但返回一个对象而不是字符串?