我在学习Ruby时正在研究一个简单的Pi Generator,但我在RubyMine 6.3.3上一直得到NoMethodError,所以我决定尽可能简单地创建一个新项目和新类,并且我 STILL < / strong>获取NoMethodError。有什么原因吗?
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)
答案 0 :(得分:6)
您已定义了实例方法,并尝试将其称为类的方法。因此,您需要使方法hello
成为类方法,而不是类Methods
的实例方法。
class Methods
def self.hello(player)
print "Hello, " << player
end
hello("Annie")
end
或者,如果您想将其定义为实例方法,请按以下方式调用它:
class Methods
def hello(player)
print "Hello, " << player
end
end
Methods.new.hello("Annie")
答案 1 :(得分:3)
您尝试将实例方法作为类方法调用。
这里有一些代码说明了ruby中两者之间的区别:
class Person
# This is a class method - note it's prefixed by self
# (which in this context refers to the Person class)
def self.species
puts 'Human'
# Note: species is OK as a class method because it's the same
# for all instances of the person class - ie, 'Bob', 'Mary',
# 'Peggy-Sue', and whoever else, are ALL Human.
end
# The methods below aren't prefixed with self., and are
# therefore instance methods
# This is the construct, called automatically when
# a new object is created
def initialize(name)
# @name is an instance variable
@name = name
end
def say_hello
puts "Hello from #{@name}"
end
end
现在尝试一下,调用方法......
# Call a class method...
# We're not referring to any one 'instance' of Person,
Person.species #=> 'Human'
# Create an instance
bob = Person.new('Bob')
# Call a method on the 'Bob' instance
bob.say_hello #=> 'Hello from Bob'
# Call a method on the Person class, going through the bob instance
bob.class.species #=> 'Human'
# Try to call the class method directly on the instance
bob.species #=> NoMethodError
# Try to call the instance method on the class
# (this is the error you are getting)
Person.say_hello #=> NoMethodError
答案 2 :(得分:1)
您已经创建了一个实例方法,但是您正在调用一个类方法。要调用hello("Annie")
,您必须创建一个方法实例。例如:
class Methods
def self.hello(player)
print "Hello, " << player
end
end
my_method = Methods.new
my_method.hello("Annie")
这会输出Hello, Annie
答案 3 :(得分:0)
通过使用 def method_name args 定义方法,您定义的实例方法将包含在该类的每个对象中,但不包含在类本身中。
另一方面,通过 def self.method_name args ,您将获得一个直接在类中的类方法,而无需从中实例化对象。
所以如果你有这个:
Class Test
def self.bar
end
def foo
end
end
您可以这样执行实例方法:
a = Test.new
a.foo
至于班级应该是:
Test.foo