When is the Enumerator::Yielder#yield method useful?

前端 未结 4 1047
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 12:03

The question \"Meaning of the word yield\" mentions the Enumerator::Yielder#yield method. I haven\'t used it before, and wonder under what circumstances it would be

4条回答
  •  天命终不由人
    2021-02-13 12:17

    It seems to be useful when you have multiple objects you want to enumerate over, but flat_map isn't suitable, and you want to chain the enumeration with another action:

    module Enumerable
      def count_by
        items_grouped_by_criteria = group_by {|object| yield object}
        counts = items_grouped_by_criteria.map{|key, array| [key, array.length]}
        Hash[counts]
      end
    end
    
    def calculate_letter_frequencies
      each_letter.count_by {|letter| letter}
    end
    
    def each_letter
      filenames = ["doc/Quickstart", "doc/Coding style"]
      # Joining the text of each file into a single string would be memory-intensive
      enumerator = Enumerator.new do |yielder|
        filenames.each do |filename|
          text = File.read(filename)
          text.chars.each {|letter| yielder.yield(letter)}
        end
      end
      enumerator
    end
    
    calculate_letter_frequencies
    

提交回复
热议问题