Last active
June 1, 2018 19:14
Star
You must be signed in to star a gist
Enumerate over multiple files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MultiFile | |
include Enumerable | |
def initialize(filenames_or_handles, open_mode: 'r:utf-8') | |
@names_and_handles = Array(filenames_or_handles).map do |fn| | |
if fn.kind_of?(IO) | |
name = if fn.respond_to? :to_path | |
fn.to_path | |
else | |
'<IO>' | |
end | |
[name, fn] | |
else | |
[fn, File.open(fn, open_mode)] | |
end | |
end | |
end | |
def each | |
return enum_for(:each) unless block_given? | |
self.each_with_filename do |line, _fn| | |
yield line | |
end | |
end | |
def each_with_filename | |
return enum_for(:each_with_filename) unless block_given? | |
self.each_with_filename_and_index do |line, fn, _i| | |
yield line, fn | |
end | |
end | |
def each_with_filename_and_index | |
return enum_for(:each_with_filename_and_index) unless block_given? | |
@names_and_handles.each do |fn, fh| | |
fh.each_with_index {|line, i| yield line, fn, i} | |
end | |
ensure | |
@names_and_handles.each {|fn, fh| fh.close} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment