0

我写了一个类似于以下的模块:

module One
  class Two
    def self.new(planet)
      @world = planet
    end
    def self.hello
      "Hello, #{@world}"
    end
  end
end

我打算通过以下方式操作模块:

t = One::Two.new("World")
puts t.hello

但是,显然self.hello不在t's 范围内。我意识到我可以做到以下几点:

t = One::Two
t.new("World")
puts t.hello

以前的方法感觉不对,所以我正在寻找替代方法。

4

2 回答 2

1
module One
  class Two
    # use initialize, not self.new
    # the new method is defined for you, it creates your object
    # then it calls initialize to set the initial state.
    # If you want some initial state set, you define initialize.
    # 
    # By overriding self.new, One::Two.new was returning the planet,
    # not an initialized instance of Two.
    def initialize(planet)
      @world = planet
    end

    # because One::Two.new now gives us back an instance,
    # we can invoke it
    def hello
      "Hello, #{@world}"
    end
  end
end

t = One::Two.new 'World'
t.hello # => "Hello, World"
于 2012-06-08T04:00:16.870 回答
1

您应该创建一个initialize方法而不是self.new创建一个类的对象。SomeClass.new将调用该initialize方法。

如果你想访问实例变量,你应该使用实例方法。所以而不是def self.hellodo def hello。如果你想要类方法,你也应该使用类变量。这样做,而不是@some_var使用@@some_var.

于 2012-06-08T02:49:21.007 回答