2017-12-17 2 views
1

나는 다음과 같이 내가 Enumerable 모듈을 포함 시켰 클래스가 있습니다 블록이 주어진에도 불구하고 블록을 산출하도록 요청 실패

class Paragraph 
    include Enumberable 
    attr_accessor :error_totals 

    def initialize(text, error_totals) 
    @original = text 
    @error_totals = error_totals 
    end 

    def each 
    error_totals.each {|category, total| yield category, total } 
    end 

    def totals 
    each.reduce(0) {|t,(category,total)| to += total } 
    end 
end 

나는 내가 이유를 다음과 같은 오류를 이해하지 못하는 얻을를 :

LocalJumpError: 
    no block given (yield) 

그러나 나는 다음 작업을 수행 할 때 그것은 작동 :

def total_errors_per(number_of_words:) 
    result = 0.0 
    each {|category, total| result += total.to_f/original.word_count*number_of_words} 
    result 
end 

하는 이유는 캘리포니아를 줄일 않습니다 이 문제를 사용합니까? 줄이기 위해 호출 후 블록을 전달하고 있습니다. 정말이 문제를 이해함으로써 Enumberable 모듈을 올바르게 사용하는 방법을 알고 싶습니다. 당신의 each 구현에서

답변

1

당신은 블록이 주어진 여부 및 each.reduce 호출 each더 블록을받지 여부에 상관없이 yield를 호출합니다. 더 블록이 주어지지 않은 경우

하나 열거자를 반환해야합니다 :

def each 
    return enum_for(:each) unless block_given? 
    error_totals.each {|category, total| yield category, total } 
end 
+0

나는 더 블록이 제공되지 않는 경우 열거 객체가 자동으로 반환됩니다 – chell

+0

아무 것도 컴퓨터 과학에서 자동으로 수행되고 있지 생각했다. CPU는 당신의 소망과 꿈이 아닌 처리 지침을 이해합니다. – mudasobwa

+0

사실이 아닙니다. 데이비드 블랙 (David Black)의 "잘 알려진 루비스트 (The Well Grounded Rubyist)"에 따르면 316 페이지의 "이터레이터는 블록없이 호출 될 때 열거자를 반환합니다."라고 말합니다. – chell

관련 문제