Bạn đang cố gắng gọi một phương thức thể hiện như một phương thức lớp.
Dưới đây là một số mã để minh họa sự khác biệt giữa hai trong 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
Và bây giờ thử nó ra, kêu gọi các phương pháp ...
# 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
Nguồn
2014-10-14 10:31:57
bạn đang gọi phương thức bên trong định nghĩa lớp. Tôi không chắc chắn ý định của nó. – Tensibai
Tôi không chắc chắn về nền tảng/mức độ kinh nghiệm của bạn trong lập trình OO, vì vậy chỉ cần kiểm tra: bạn có hiểu sự khác biệt giữa các lớp và các cá thể (và các phương thức lớp và các phương thức mẫu) không? Câu trả lời giả định bạn làm ... –