Ruby Koans : 기호 목록을 문자열로 변환하는 이유
Ruby Koans의 about_symbols.rb에서이 테스트를 참조하고 있습니다. https://github.com/edgecase/ruby_koans/blob/master/src/about_symbols.rb#L26
def test_method_names_become_symbols
symbols_as_strings = Symbol.all_symbols.map { |x| x.to_s }
assert_equal true, symbols_as_strings.include?("test_method_names_become_symbols")
end
# THINK ABOUT IT:
#
# Why do we convert the list of symbols to strings and then compare
# against the string value rather than against symbols?
그 목록을 먼저 문자열로 변환해야하는 이유는 무엇입니까?
이것은 기호가 작동하는 방식과 관련이 있습니다. 각 기호에 대해 실제로는 하나만 존재합니다. 이면에서 기호는 이름 (콜론으로 시작)으로 참조되는 숫자입니다. 따라서 두 기호의 동일성을 비교할 때이 기호를 참조하는 식별자의 내용이 아니라 객체 ID를 비교 하는 것입니다.
간단한 테스트를했다면 : test == "test" 는 거짓이됩니다. 따라서 지금까지 정의 된 모든 기호를 배열로 모으려면 비교하기 전에 먼저 문자열로 변환해야합니다. 그렇게하면 해당 심볼의 단일 인스턴스가 생성되고 존재 여부를 테스트하는 심볼로 목록을 "오염"시킬 수 있기 때문에 반대의 방법 (비교하려는 문자열을 먼저 심볼로 변환) 할 수 없습니다.
도움이되기를 바랍니다. 테스트 중에 실수로 심볼을 만들지 않고 심볼의 존재 여부를 테스트해야하기 때문에 이것은 약간 이상한 것입니다. 일반적으로 그런 코드는 보이지 않습니다.
왜냐하면 당신이
assert_equal true, all_symbols.include?(:test_method_names_become_symbols)
(루비 구현에 따라) 자동으로 true가 될 수 있습니다 :test_method_names_become_symbols
. 이 버그 보고서를 참조하십시오 .
위의 두 답변 모두 정확하지만 위의 Karthik의 질문에 비추어 볼 때 기호를 include
메서드에 정확하게 전달하는 방법을 보여주는 테스트를 게시 할 것이라고 생각했습니다.
def test_you_create_a_new_symbol_in_the_test
array_of_symbols = []
array_of_symbols << Symbol.all_symbols
all_symbols = Symbol.all_symbols.map {|x| x}
assert_equal false, array_of_symbols.include?(:this_should_not_be_in_the_symbols_collection) #this works because we stored all symbols in an array before creating the symbol :this_should_not_be_in_the_symbols_collection in the test
assert_equal true, all_symbols.include?(:this_also_should_not_be_in_the_symbols_collection) #This is the case noted in previous answers...here we've created a new symbol (:this_also_should_not_be_in_the_symbols_collection) in the test and then mapped all the symbols for comparison. Since we created the symbol before querying all_symbols, this test passes.
end
Koans에 대한 추가 참고 사항 : puts
아무것도 이해하지 못하는 경우 명령문과 사용자 지정 테스트를 사용하십시오. 예를 들어 다음과 같은 경우 :
string = "the:rain:in:spain"
words = string.split(/:/)
무엇이 될지 words
모르 시겠습니까?
puts words
실행 rake
명령 줄에서. 마찬가지로 위에서 추가 한 것과 같은 테스트는 Ruby의 일부 뉘앙스를 이해하는 데 도움이 될 수 있습니다.
참고 URL : https://stackoverflow.com/questions/4686097/ruby-koans-why-convert-list-of-symbols-to-strings
'your programing' 카테고리의 다른 글
중첩 된 'for'루프의 수에 제한이 있습니까? (0) | 2020.10.09 |
---|---|
누군가 잘 구성된 crossdomain.xml 샘플을 게시 할 수 있습니까? (0) | 2020.10.09 |
Angular JS 필터가 같지 않음 (0) | 2020.10.09 |
메모장 ++ 증분 교체 (0) | 2020.10.09 |
C 또는 C ++로 구조체를 반환하는 것이 안전합니까? (0) | 2020.10.09 |