2014-09-17 4 views
0

이것은 간단한 질문 일 것입니다. 제 생각에는 너무 오랫동안 코드를 쳐다 보면서 두뇌 방귀를 피우고있는 것 같습니다.로컬 변수 레일

jsonlasttengamesopp["games"].each do |opp| 
    if opp["gameId"] == x["gameId"] 
    opponentkills = opp["stats"]["championsKilled"] 
    opponentassists = opp["stats"]["assists"] 
    opponentdeaths = opp["stats"]["numDeaths"] 
    binding.pry #Binding.pry number 1 
    break 
    end 
    end 

binding.pry #Binding.pry number 2 

첫 번째 binding.pry 나에게 올바른 opponentkills, 어시스트 사망 ..를 제공

내가 opponentkills 호출 할 때 두 번째 binding.pry 날이 오류를 제공합니다

NameError: undefined local variable or method `opponentkills' for #<Class:0x007f46b0cab428> 

I을 이 루프 밖에서 상대방에게 전화를 걸 수 있어야합니다. 하지 않아도 될까요?

답변

2

각 블록은 자체 바인딩을 만듭니다. 즉, 블록 내에서 생성 된 변수는이 블록 외부에서 액세스 할 수 없습니다. 그러나 각 블록은 생성 된 바인딩을 전달하므로 외부 변수에 액세스 할 수 있습니다. 그래서 대신이 작업을 수행 할 경우 :

opponentkills = nil 
jsonlasttengamesopp["games"].each do |opp| 
    if opp["gameId"] == x["gameId"] 
    opponentkills = opp["stats"]["championsKilled"] 
    opponentassists = opp["stats"]["assists"] 
    opponentdeaths = opp["stats"]["numDeaths"] 
    binding.pry #Binding.pry number 1 
    break 
    end 
end 

binding.pry #Binding.pry number 2 

블록은 바인딩 내에서 새 로컬 변수를 생성하지 않지만 바인딩 외부에서 변수를 사용합니다.

+0

대단히 감사합니다! – user3591126