January 15th, 2014, 08:09 PM
Undefined Local Variable or Method
Today, I started to try to learn ruby. When I went to make my first method, I kept receiving an error "undefined local variable or method."
I tried looking up how to make methods in Ruby online, so that I would be sure its not my own fault. I copy pasted several examples into my ide, all of which returned the same error.
I made a simple method (below) and I get the same error: <class:TEST>': undefined local variable or method `greeter' for TEST:Class (NameError)
The built in ruby methods work fine. Is there something wrong with what I'm doing?
January 15th, 2014, 10:59 PM
I think there's a general misunderstanding with regard to object-oriented programming.
The methods you define within a class belong to the instances of this class, not the class itself. So when you create a TEST object, this object will have a greeter method:
# now instantiate the class
test = Test.new
# this object has a greeter() method
It works just like in other object-oriented languages like Java, C++, whatever.
If you want to add a method to the class itself, that's very different. You now have to define a so called “singleton method” for the class object:
# define a singleton method for the Test class object
# instead of hard-coding the "Test", you could also write "self"
puts 'The class says Hi.'
# the Test class has a class_greeter() method
Most other languages don't have this concept of singleton methods. They use a special keyword named "static" instead.