我在一個單獨的文件中定義了一個類,並且需要它並創建了一個object.but似乎initialize函數執行了兩次。要求一個類導致雙重執行
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頭等),結果是一樣的:
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"
有什麼想法?
因爲你包含'a.rb'並且再次執行它。 – texasbruce 2013-03-05 23:31:47