【问题标题】:NameError in RubyRuby 中的名称错误
【发布时间】:2011-09-23 02:34:27
【问题描述】:

对于这段代码:

class myBaseClass
  def funcTest()
    puts "baseClass"
  end
end
myBaseClass.new.funcTest

我收到一个错误:

NameError: undefined local variable or method `myBaseClass' for main:Object
from c:/Users/Yurt/Documents/ruby/polymorphismTest.rb:9
from (irb):145:in `eval'
from (irb):145
from c:/Ruby192/bin/irb:12:in `<main>'
irb(main):152:0> x=myBaseClass.new

当我尝试x=myBaseClass.new 时,我得到:

NameError: undefined local variable or method `myBaseClass' for main:Object from (irb):152

有人遇到过这个问题吗?我认为我的代码不会出错。

【问题讨论】:

  • Emacs 是无关紧要的。相应地进行了编辑。

标签: ruby class


【解决方案1】:

在 ruby​​ 中,包括类名在内的所有常量都必须以大写字母开头。 myBaseClass 将被解释为未定义的局部变量。 MyBaseClass 可以正常工作。

【讨论】:

  • 有趣的是,你可以这样做:class Foo; end; f = Foo; f.new
  • 那是因为类是一个对象,可以赋值给一个变量。您可以定义和使用一个类,而无需将其分配给常量:f=Class.new; f.new 为您提供驻留在局部变量 f 中的未命名类的实例@
【解决方案2】:

你的类名应该以大写开头,下面的工作代码

class MyBaseClass
  def funcTest()
   puts "baseClass"
 end
end



MyBaseClass.new.funcTest

【讨论】:

    【解决方案3】:

    您的代码错误。在 Ruby 中,类名必须以大写字母开头。

    class MyBaseClass
    

    修复它。

    我不明白的是,您没有像我一样收到明确的错误消息。

    【讨论】:

    • 我在 windows 上运行 ruby​​ 1.9.2,从 oneclick 安装程序获得。出于好奇,我应该得到什么错误消息?
    • 我的 1.9.2 p180 (ubuntu) 说:SyntaxError: (irb):1: class/module name must be CONSTANT
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多