2014-11-28 4 views
1

다음 루비 튜토리얼 http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/41-exceptions/lessons/93-throw-and-catch을 만들고 있습니다. 대신, 검색이라는 방법에서 발견 타일을 반환'던지기'의 대안을 고려하는 방법은 무엇입니까?

변경 마지막 예 : 운동 중 하나는 저를 묻는다. 검색은 평면도를 매개 변수로 받아야합니다.

운동 (운동 전) 마지막 예와 유사하며 다음과 같습니다

candy = catch(:found) do 
    floor.each do |row| 
    row.each do |tile| 
     throw(:found, tile) if tile == "jawbreaker" || tile == "gummy" 
    end 
    end 
end 
puts candy 

운동 아래 힌트가 :

방법으로 '캐치'라인을 교체하십시오 정의와 '반환'과 함께 'throw'행 .

와 나는 그렇게 :

candy = search do 
    floor.each do |row| 
    row.each do |tile| 
     return tile if tile == "jawbreaker" || tile == "gummy" 
    end 
    end 
end 
puts candy 

하지만 오류가 발생했습니다. 아무도 나에게 긍정적 인 결과를 얻는 방법을 말할 수 있습니까? 그리고 추가 질문 : throw (catch) (catch)와 catch (catch) 코드에서 서로 다른 throw (: found, tile)가있는 이유는 무엇입니까?

답변

0

그들은 당신이 시도하려는 당신이 언급 한 힌트를 볼 수 없지만, 그런 것 같아요 :

candy = floor.each do |row| 
    row.each do |tile| 
    return tile if tile == "jawbreaker" || tile == "gummy" 
    end 
end 
puts candy 

LocalJumpError 당신받을하기. 여기서는 return을 사용할 수 없으므로 break을 사용할 수는 있지만 내부 순환에서만 걸리게되므로 throw - catch을 사용하여 중첩 루프에서 빠져 나옵니다.

3

마지막 예제를 변경하여 찾은 타일을 검색이라는 메서드에서 반환합니다. 검색은 평면도를 매개 변수로 받아야합니다.

이 연습에서는 매개 변수로 평면도를받는 search라는 메서드를 구현하는 것으로 알고 있습니다. 모든이가 지금

candy = search(floor) 
puts candy 

: 그것은 반환 사탕의 결과, 그래서 호출 코드는 다음과 같이해야한다

def search(floor) 

: 그래서 당신은 필요 검색라는 메소드를 구현 왼쪽 메서드 본체를 구현하는 것입니다 반환 결과. 올바른 결과를 반환하려면 술어 (tile == "jawbreaker" || tile == "gummy")가 true이되는 즉시 row.each을 중지해야합니다. each으로는 불가능하므로 다른 것으로 바꿔야합니다.

row.find { |tile| tile == "jawbreaker" || tile == "gummy" } 

내가 영업 이익 운동으로 외부 루프 (floor.each)에 필요한 변화를 떠날 것이다 : find은 조건과 일치하는 첫 번째 요소를 반환합니다.

1

다음과 같은 시도는 연습 문제에 전달됩니다.

def search(floor) 
    floor.each do |row| 
     row.each do |tile| 
     return tile if tile == "jawbreaker" || tile == "gummy" 
     end 
    end 
end 

candy = ->(flr) { 
    search(flr) 
} 

puts candy 
0

괜찮 았어. 그래서 나에게 도움이되었다. 이 코드는 루비로 멀리까지 도달하면 꽤 자명하다.

floor = [["blank", "blank", "blank"], 
    ["gummy", "blank", "blank"], 
    ["blank", "blank", "blank"]] 
def search(floor) 
floor.each do |row| 
row.each do |tile| 
    return tile if tile == "jawbreaker" || tile == "gummy" 
end 
end 
end 

candy = lambda {|floor| search(floor)} 
puts candy.call(floor) 
관련 문제