2014-09-21 68 views
1

我是Ruby新手,使用eclipse,DLTK ruby​​插件和Ruby 2.0。我创建称为AModule.rb一个红宝石模块文件,其具有的代码:了解ruby模块

require 'AModule' 
puts AModule::aConstant 

在上面的代码的第二行:

module AModule 
    aConstant = 7 
end 

这是从在同一个项目的测试红宝石脚本调用,我得到了错误in '<main>': undefined local variable or method 'aModule' for main:Object (NameError)

我跟着我的codeacademy教程,所以我没想到会发生这种情况。我在这里犯的错误是什么? PS:其实,我想命名我的模块文件** aM ** odule.rb而不是** AM ** odule.rb。但是,DLTK插件悄然使第一个字母大写。这可能是一个错误?

+0

无法复制。 – sawa 2014-09-21 07:39:43

+0

@sawa - 其实我已经定义了它。我在put中犯了一个小小写错误。我现在修好了。同样的错误依然存在。如果您在我的问题中看不到任何错误或缺点,您可以请我高举零点吗?谢谢。 – 2014-09-21 07:40:49

+0

我的评论适用于编辑后的问题(我的删除答案适用于编辑前的问题)。我不会按照您的要求以任何方式进行投票。你不应该问这个问题。而且,正如我写的那样,它不能被复制。 – sawa 2014-09-21 07:42:44

回答

1

你的问题是,常量名称必须以UpperCaseLetter开头。否则Ruby会认为它是局部变量。那么它有什么问题?简而言之:这就是范围。局部变量只在其词汇范围内可见。 不变是一个完全不同的事情。常数可以通过所谓的namespace-resolution operator (::)来访问。

阅读更多关于Ruby范围的信息here

0

我用windows cmd代替了eclipse IDE。我将展示我用来查找代码错误的步骤,并最终修复它们。 DLTK插件在这里没有问题。模块文件和测试脚本位于同一个文件夹中。

LESSON -模块中的模块名称和常量名必须以大写字母开头。为什么,我不知道。

aModule.rb

module aModule 
aConstant = 7 
end 

Test.rb

require 'aModule' 
puts aModule::aConstant 

CMD:光盘插入Test.rb文件夹和ruby Test.rb 错误:``需要“:无法加载这样的文件 - tokenizer.rb(LoadError)` 帮助:Ruby 'require' error: cannot load such file

Ruby 1.9 has removed the current directory from the load path, and so you will need to do a relative require on this file, as Pascal says:

require './tokenizer' 

There's no need to suffix it with .rb, as Ruby's smart enough to know that's what you mean anyway.

我做了以下修改:

Test.rb

require './aModule' 
puts aModule::aConstant 

CMD:ruby Test.rb 错误:在aModule.rb 帮助:NameError in Ruby

我做了以下修改:

aModule.rb

module AModule # capital 
aConstant = 7 
end 

Test.rb

require './AModule' 
puts AModule::aConstant 

CMD:红宝石测试。rb 错误:undefined method 'aConstant' for AModule:Module (NoMethodError) 帮助:使用上面的链接。我认为不变也必须以资本命名。

最后工作的代码:

aModule.rb

module AModule # capital 
AConstant = 7 # capital 
end 

Test.rb

require './AModule' 
puts AModule::AConstant 

WTF是红宝石这样???以及为什么我需要在模块名称之前附加./,因为它与测试脚本位于同一个文件夹中?

+1

'。/'解释[here](http://stackoverflow.com/questions/2900370/why-does-ruby-1-9-2-remove-from-load-path-and-whats-the-alternative) – user2422869 2014-09-21 09:54:33