Ruby: NoMethodError, but why?

Annie the Eagle picture Annie the Eagle · Oct 14, 2014 · Viewed 29.2k times · Source

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)

Answer

Arup Rakshit picture Arup Rakshit · Oct 14, 2014

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 class Methods.

class Methods
  def self.hello(player)
    print "Hello, " << player
  end
  hello("Annie")
end

Or, if you want to define it as instance method then call it as below :

class Methods
  def hello(player)
    print "Hello, " << player
  end
end
Methods.new.hello("Annie")