English 中文(简体)
将同一单元本身列入Ruby?
原标题:Including the same module file within itself in Ruby?
  • 时间:2010-09-15 17:42:48
  •  标签:
  • ruby

我正在学习废墟以及模块和组合。

我尝试了以下法典。 废墟档案测试名称。

module Mod1
  def Mod1.sayHello()
    puts "Hello Mod1"
  end

end

module Mod2
  def Mod2.sayHello()
    puts "Hello Mod2"
  end
end


class TestMod
  require  file 
  Mod1.sayHello
end

t = TestMod.new

I am suprised to the output: Hello Mod1 Hello Mod1 (twice)

我没有对此做出解释,一些人能否帮助?

问题回答

You did not define your initialize method for your class (the constructor). You are simply executing Mod1.sayHello inside the class definition (it is even executed before creating the instance). Try to comment out your t = TestMod.new statement. The output will still stay visible.
Since you include the exact same file, this ends up being executed twice (the file does not get included another time afterwards; ruby prevents this). The class should look like this:

class TestMod
  def initialize
    Mod1.sayHello
  end
end

为什么要把档案列入其中? 这对我来说没有意义。

http://www.un.org。 删除了一个错误。

我建议将<代码>Mod1和Mod2在你的模块定义中改为自封。 如果改变一段时间,你就必须改变各地的名称。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...