आप एक क्लास विधि के रूप में एक उदाहरण विधि को कॉल करने की कोशिश कर रहा हूं।
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
स्रोत
2014-10-14 10:31:57
आप वर्ग परिभाषा के अंदर विधि कॉल कर रहे हैं होगा। मैं इसके इरादे से अनिश्चित हूँ। – Tensibai
मुझे ओओ प्रोग्रामिंग में आपकी पृष्ठभूमि/अनुभव के स्तर की जानकारी नहीं है, इसलिए बस जांचें: क्या आप कक्षाओं और उदाहरणों (और कक्षा विधियों और उदाहरण विधियों) के बीच अंतर को समझते हैं? जवाब आपको लगता है कि ... –