Skip to content

Instantly share code, notes, and snippets.

@billdueber
Last active June 1, 2018 19:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save billdueber/5249d0a8971e817fd4573ef17bb5dca8 to your computer and use it in GitHub Desktop.
Enumerate over multiple files
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