루비가 인스턴스 변수 대신 로컬 변수 안에 이러한 클래스를 인스턴스화/저장하는 이유는 무엇입니까?루비가 인스턴스 변수 대신 로컬 변수를 내부에 저장하고 있습니다
나는 그것이 작동하도록하려면 코드를 변경하기 전에,이 있었다 :
% 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
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
메소드가 성공하여 성공했습니다 :
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에서 인스턴스 변수를 선언하는 방식이 아니기 때문입니다. 클래스 선언에서는 인스턴스가 아니라 클래스에 있으므로 @ 변수는 자신이 생각하는 것이 아닙니다. –
그래서 기본적으로 메소드의 인스턴스 외부를 정의했기 때문에 작동하지 않았습니다. 초기화 방법의 내부에서 작업을 수행했다면 작동했을 것입니다. 권리? 음 ... 테스트의 내부에서 이것이 작동하지 않는 것처럼 보입니다 ... 좋아요, 생각합니다. 고마워. –
가장 효율적인 코드는 무엇입니까? @@ class_var 선언을 사용하거나 위에서 수행 한 방식대로 수행합니까? –