0

我可以在执行方法之前让对象重新初始化吗?我正在使用 Ruby 和 selenium 来测试一个网络应用程序,并且我正在尝试改进我的页面对象。例如

class Foo

  def initialize
    #stuff happens here 
  end

  def NewMethod
    self.initialize
    #What happens here is what I really want to happen 
  end 

end 

这是个好主意还是坏主意?还是有更好的方法来做到这一点?

4

2 回答 2

0

提前说明:方法以小写形式编写。请替换NewMethodnewmethod.

如果你尝试Foo.newmethod你会得到一个错误。

你想让我做什么?您想定义创建对象的不同可能性吗?

你可以做什么:

class Foo
  def initialize
  end

  def self.newmethod
    me = self.new
    #Some actions ...
    me #Return the (modified?) object
  end 

end 

p Foo.newmethod #->#<Foo:0xb77d58>

Time正在使用这样的东西。有Time.new, Time.gm, Time.local...

于 2012-08-30T20:37:39.997 回答
0

始终可以更改对象中包含的数据。您可以将所有初始化逻辑放入一个附加方法中,然后从您的自定义方法中调用它。

通常,您尝试做的事情听起来不是一个好主意...

于 2012-08-30T18:47:02.737 回答