2014-02-26 4 views
0

레일즈에서 해시 작업을 시도하고 있습니다. each을 실행하면 예기치 않은 결과가 발생합니다. 각 요소의 '이름'에 액세스하려고합니다.해시에서 각각을 사용할 때의 오류

나는 some_files라는 해시, 그것은 단지 한 요소와이 시간에 시작 :

logger.debug some_files 
# Outputs this: {"0"=>{"name"=>"index.html", "contents"=>""}} 
# Ok cool, the first level of this array seems to only have 1 element called "0". 

가 지금은 (때로는 1 개 이상의 요소가 때문에) 그것을 통해 반복합니다.

some_files do |some_file| 
    logger.debug some_file 
    # Outputs this: ["0", {"name"=>"index.html", "contents"=>""}] 
    # Weird, why do I get "0" still? And why does it appear to be a separate element? 

    logger.debug some_file.name 
    # Outputs an error: NoMethodError (undefined method `name' for ["0", {"name"=>"index.html", "contents"=>""}]:Array): 
end 
+1

downvote 경우 적어도 downvoting 이유에 대한 의견을주십시오. 나는 문서를보고 내 실수를 보지 못했다. http://ruby-doc.org/core-2.1.1/Array.html#method-i-each –

+0

'some_file.last [ "name"]'이 아니어야합니까? – PericlesTheo

+0

어떻게'each_'을 사용하지 않고'some_files'를 반복 할 수 있습니까? 나는'some_files do | some_file | ... ' – mdesantis

답변

3

Ruby에서 .each를 사용하여 해시를 반복하는 경우 모두 키와 값이 블록에 전달됩니다. 1 개의 파라미터만을 지정하면 (자), 대신에 키와 값을 포함한 배열이됩니다. 따라서, 적절한 사용은 다음과 같습니다 value 이후

hash = {"0"=>{"name"=>"index.html", "contents"=>""}} 

hash.each do |key, value| 
    puts "key = #{key}, value = #{value}" 
    # => key = 0, value = {"name"=>"index.html", "contents"=>""}  
end 

또한 해시, 당신은 같은 방법을 반복 할 수 있습니다.

1

제 1 출력은 :

{"0"=>{"name"=>"index.html", "contents"=>""}} 

해시 아닌 배열이다. 두 번째 출력은 배열입니다.

some_files.each do |some_file| 
    # you get 
    a = ["0", {"name"=>"index.html", "contents"=>""}] 
    # which is an array, containing a string and a hash and you could get the name via: 
    name = a[1]["name"] 
end 

배열에 메서드 이름이 없으므로 undefined method name이 표시됩니다.

지금까지

이상한, 같은 난 아직도 "0"이유는 무엇입니까? 그리고 왜 그것은 분리 된 요소 인 것처럼 보입니까?

무슨 뜻인지 이해가되지 않습니다.

+0

감사합니다. sytycs - 질문에서 "해시"로 "어레이"를 수정했습니다. 어떻게 '각'이 '0'과 두 번째 부분을 나눌까요? 각각 해쉬의 첫 단계를 거치지 않을까요? –

+0

@DonnyP some_files는 중첩 된 해시입니다. 보통 두 개의 블록 변수'key'와'value'를 전달합니다. 하나만 전달하면 Ruby는 어떻게 든 그것을 보충해야합니다. 그래서 블록 변수로 표현 된 배열에 모든 것을 넣습니다. – PericlesTheo