我正在学习来自java的ruby dev,我不明白为什么我会得到以下错误.@test是一个类变量,所以我应该能够输出它?
C:/Projects/RubyPlayground/Tester.rb:6:in `test': wrong number of arguments (ArgumentError)
from C:/Projects/RubyPlayground/Tester.rb:6:in `testMethod'
from C:/Projects/RubyPlayground/Tester.rb:10
Run Code Online (Sandbox Code Playgroud)
资源:
class Tester
@test = "here"
def testMethod()
puts test
end
s = Tester.new()
s.testMethod()
end
Run Code Online (Sandbox Code Playgroud)
在这种情况下,@ test成为类实例变量,并与类对象(不是类实例!)相关联.如果你想@test的行为像java字段,你必须使用'initialize'方法:
class Tester
def initialize
@test = "here"
end
def testMethod
puts @test
end
end
s = Tester.new()
s.testMethod
Run Code Online (Sandbox Code Playgroud)