ruby 使用Enumerable逐行迭代文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 使用Enumerable逐行迭代文件相关的知识,希望对你有一定的参考价值。

module ReadIngredients
  class << self
    include Enumerable

    def each
      while input = gets.chomp
        break if end_of_input?(input)

        yield input
      end
    end

    alias_method :with_object, :each_with_object

    private

    def end_of_input?(input)
      input == 'done'
    end
  end
end

ingredients = ReadIngredients.with_object([]) do |ingredient, ingredients|
  ingredients << ingredient
end
puts ingredients

以上是关于ruby 使用Enumerable逐行迭代文件的主要内容,如果未能解决你的问题,请参考以下文章