I was working on a simple Pi Generator while learning Ruby, but I kept getting NoMethodError on RubyMine 6.3.3, so I decided to make a new project and new class with as simple as possible, and I STILL get NoMethodError. Any reason?
class Methods
def hello (player)
print "Hello, " << player
end
hello ("Annie")
end
And the error I get is:
C:/Users/Annie the Eagle/Documents/Coding/Ruby/Learning Environment/methods.rb:5:in `<class:Methods>': undefined method `hello' for Methods:Class (NoMethodError)
You have defined an instance method and are trying to call it as a method of a class. Thus you need to make the method
hello
a class method, not an instance method of the classMethods
.Or, if you want to define it as instance method then call it as below :
You're trying to call an instance method as a class method.
Here's some code that illustrates the difference between the two in ruby:
And now try it out, calling the methods...
By defining a method with def method_name args you are defining a instance method that will be included in every object of that class, but not in the class itself.
On the other hand, by def self.method_name args you will get a class method that will be directly in the class, without the need of instanciate an object from it.
So If you have this:
You can execute the instance method this way:
And as for the class one should be:
You've created an instance method, but you're calling a class method. In order to call
hello("Annie")
, you have to make an instance of Methods. For instance:This would output
Hello, Annie