为什么 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, @cv.@celsius(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
我决定尝试在每个方法中实例化类(Convert)并成功:
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
ddouglas@coders:~/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 在第一次尝试时不会将实例变量识别为对象?