Skip to content

Instantly share code, notes, and snippets.

@julian-a-avar-c
Last active May 24, 2021 03:55
Show Gist options
  • Save julian-a-avar-c/511bebf7ee5ab1f8d3ccdc57dd6e6d7b to your computer and use it in GitHub Desktop.
Save julian-a-avar-c/511bebf7ee5ab1f8d3ccdc57dd6e6d7b to your computer and use it in GitHub Desktop.
zip lines of two files
# under CC0 License
# zips the lines of two files
# don't know how to extend ruby
# instead made a function
# this works cuz `File.open(file, "r").each` return an Enumerable of lines
$i = { a: "#{__dir__}/a.txt", b: "#{__dir__}/b.txt" }
$o = "#{__dir__}/o.txt"
def file_zip(a, b)
return File.open(a, "r").each.zip(File.open(b, "r").each)
end
o = file_zip($i[:a], $i[:b]).map { |zipped_lines| zipped_lines.join }
File.open($o, "w") { |file| file.write(o.join) }
@gr33n7007h
Copy link

IO.write('c.txt', IO.foreach('a.txt').zip(IO.foreach('b.txt')).join)

@julian-a-avar-c
Copy link
Author

@gr33n7007h don't you need to close an IO after opening it like that?

@gr33n7007h
Copy link

Both IO.write and IO.foreach ensure that the underlying io is closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment