繁体   English   中英

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

[英]How do I manipulate a variable that has been set to an object?

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

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.hellot的范围。 我意识到我可以做以下事情:

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

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

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

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

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM