Ruby:NoMethodError,但为什么呢? [英] Ruby: NoMethodError, but why?
问题描述
我在学习 Ruby 时正在开发一个简单的 Pi 生成器,但是我在 RubyMine 6.3.3 上一直遇到 NoMethodError,所以我决定用尽可能简单的方式创建一个新项目和新类,并且我仍然 得到 NoMethodError.有什么理由吗?
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
我得到的错误是:
C:/Users/Annie the Eagle/Documents/Coding/Ruby/Learning Environment/methods.rb:5:in `<class:Methods>': undefined method `hello' for Methods:Class (NoMethodError)
推荐答案
您已经定义了一个实例方法,并试图将其作为一个类的方法来调用.因此,您需要使方法 hello
成为类方法,而不是 Methods
类的实例方法.
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")
这篇关于Ruby:NoMethodError,但为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!