我是 Ruby 新手。我的示例代码给了我这个异常(exception):
C:/Users/abc/RubymineProjects/Sample/hello.rb:5:in `<class:Hello>': undefined method `first_method' for Hello:Class (NoMethodError)
from C:/Users/abc/RubymineProjects/Sample/hello.rb:1:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
进程结束,退出代码为 1
我的代码是:
class Hello
def first_method
puts "Hello World"
end
first_method()
end
我正在使用 RubyMine 4.5.4。
最佳答案
问题是您试图在类上调用 first_method
—— 而 first_method
是一个实例方法。要调用实例方法,您需要使用类的实例。要创建该类的实例,您可以使用 SomeClass.new
。因此,要使用您的方法,请尝试以下代码(与@megas 相同的代码):
class Hello
def first_method
puts "Hello World"
end
end
Hello.new.first_method
关于ruby - 尝试在 Ruby 中调用方法时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13361426/