为什么Ruby迫使我在局部变量而不是实例变量中实例化/存储这些类?Ruby正在本地变量中存储类而不是实例变量
之前,我改变了我的代码,使其功能,我有这样的:
require 'test/unit'
require 'converter'
class TestConverter < Test::Unit::TestCase
@cv = Convert.new
def test_celsius
assert_equal(100.0, @cv.celsius(212))
assert_equal(0.0, @[email protected](32))
end
def test_fahrenheit
assert_equal(212.0, @cv.fahrenheit(100))
assert_equal(32.0, @cv.fahrenheit(0))
end
end
其抛出这个错误:
% ruby -I. converter_test.rb ✭
Run options:
# Running tests:
EE
Finished tests in 0.000616s, 3246.7638 tests/s, 0.0000 assertions/s.
1) Error:
test_celsius(TestConverter):
NoMethodError: undefined method `celsius' for nil:NilClass
converter_test.rb:9:in `test_celsius'
2) Error:
test_fahrenheit(TestConverter):
NoMethodError: undefined method `fahrenheit' for nil:NilClass
converter_test.rb:14:in `test_fahrenheit'
2 tests, 0 assertions, 0 failures, 2 errors, 0 skips
我决定尝试实例每个内部类(转换)方法并且成功:
require 'test/unit'
require 'converter'
class TestConverter < Test::Unit::TestCase
#@cv = Convert.new
#instantiated the class in each method instead of here
def test_celsius
cv = Convert.new
assert_equal(100.0, cv.celsius(212))
assert_equal(0, cv.celsius(32))
end
def test_fahrenheit
cv = Convert.new
assert_equal(212, cv.fahrenheit(100))
assert_equal(32, cv.fahrenheit(0))
end
end
[email protected]:~/Develop/davincicoders$ ruby -I. converter_test.rb
Run options:
# Running tests:
..
Finished tests in 0.001894s, 1055.9149 tests/s, 2111.8298 assertions/s.
2 tests, 4 assertions, 0 failures, 0 errors, 0 skips
为什么Ruby不能识别实例变量为第一次尝试中的对象?
因为这不是你在Ruby中声明实例变量的方式。在类声明中,你在类中,而不是一个实例,所以@variable不是你所相信的。 –
所以基本上它没有工作,因为我定义了方法外的实例。如果我在初始化方法中完成了它,它会起作用。对?嗯....在测试中,这似乎并没有工作......好吧,我想我明白了。多谢你们。 –
哪一个会是最有效的代码?使用@@ class_var声明或以我上面所做的方式进行操作? –