如何操作已设置为对象的变量?

时间:2012-06-08 02:30:51

标签: ruby class module function

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

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的范围内。我意识到我可以做到以下几点:

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

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

2 个答案:

答案 0 :(得分:1)

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

如果要访问实例变量,则应使用实例方法。因此,而不是def self.hellodef hello。如果你想要类方法,你也应该使用类变量。为此,请使用@some_var而不是@@some_var

答案 1 :(得分: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"