1

我在一个单独的文件中定义了一个类并需要它并创建了一个对象。但似乎初始化函数执行了两次。

a.rb:

Dir["#{File.dirname(__FILE__)}/*.rb"].each do |f| require(f) end
object = First.new

b.rb(这是必需的):

class First
  def initialize
    p "Hello"
  end
end

结果:

"Hello"
"Hello"

如果我说我测试了其他东西,它会变得更有趣。我将 b.rb 代码放在 a.rb 中(我的意思是我在 a.rb 中定义了 First class),结果是一样的:

a.rb:

Dir["#{File.dirname(__FILE__)}/*.rb"].each do |f| require(f) end #I now this line is useless

class Second
  def initialize
    p "Hello"
  end
end
object = Second.new



 "Hello"
 "Hello"

但是当我删除第一行(需要代码)(这在第二次测试中没用(因为我们在 a.rb 中定义了类,所以 b.rb 变得无用))一切都很好

a.rb:

#Dir["#{File.dirname(__FILE__)}/*.rb"].each do |f| require(f) end #now it is not executed.


class Second
  def initialize
    p "Hello"
  end
end
object = Second.new

"Hello"

任何的想法?!

4

1 回答 1

1

为什么不只需要你需要的文件而不是该路径中的所有 .rb 文件?如果你改变

Dir["#{File.dirname(__FILE__)}/*.rb"].each do |f| require(f) end

require 'b.rb'

它应该按预期工作

问题是您至少会同时包含 a 和 b rb 文件,这可能就是问题所在

您也可能在该文件夹中有另一个 .rb 文件,该文件在初始化时也会发送“Hello”作为输出。

请记住,您的要求包括该文件夹中的所有 rb 文件。即结果ls *.rb

于 2013-03-05T22:24:41.273 回答