28

For this piece of code:

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

I am getting an error:

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

When I tryx=myBaseClass.new, I get:

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

Has someone already encountered this problem? I don't think my code can be wrong.

edgerunner
  • 14,613
  • 2
  • 58
  • 69
S4M
  • 4,401
  • 6
  • 35
  • 46

4 Answers4

63

In ruby, all constants including class names must begin with a capital letter. myBaseClass would be interpreted as an undefined local variable. MyBaseClass would work properly.

edgerunner
  • 14,613
  • 2
  • 58
  • 69
  • 7
    Interestingly, you're allowed to do this: `class Foo; end; f = Foo; f.new` – jtbandes Jun 26 '11 at 20:32
  • 4
    That's because a class is an object and can be assigned to a variable. You can define and use a class without ever assigning it to a constant: `f=Class.new; f.new` gives you an instance of the unnamed class residing in the local variable `f` – edgerunner Jun 26 '11 at 21:31
5

Your class name should start with a capital, working code below

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



MyBaseClass.new.funcTest
mu is too short
  • 413,090
  • 67
  • 810
  • 771
Steve
  • 20,447
  • 21
  • 65
  • 91
3

Your code is wrong. Classnames must start with an uppercase in Ruby.

class MyBaseClass

fixes it.

What I don't get is how you don't get a clear error message like I do.

Bruno Rohée
  • 3,217
  • 23
  • 26
  • 1
    I am running ruby 1.9.2, on windows, gotten from the oneclick installer. Out of curiosity, what is the error message I should be getting? – S4M Jun 26 '11 at 20:25
  • my 1.9.2 p180 ( ubuntu) says: SyntaxError: (irb):1: class/module name must be CONSTANT – steenslag Jun 26 '11 at 20:57
0

Code working

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

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 18 '22 at 12:32