How you zip larger files in ruby

calendar_today agoschedule1 min read
— Originally published at dev.to

Easy way that compress files in ruby is using zip lib.

Zip::File.open('./compress.zip', create: true) do |zip|
  zip.get_output_stream("./stuff_to_ziped.pdf") do |f|
    f.puts File.read("./stuff_to_zip.pdf")
   end
end

When you need to zip larger files or when you need to perform any task that requires opening many files, good practice is to avoid loading all files into memory. To achieve this, you can use stream operations available in IO classes.

Let's look at the code above again but with a thread that monitory the memory for us.

Thread.new do
  loop do
    print "\r memory: %d MB" % "#{`ps -o rss= -p #{Process.pid}`.to_i/1024}\t"
  end
end

Zip::File.open('./compress.zip', create: true) do |zip|
  zip.get_output_stream("./stuff_to_ziped.pdf") do |f|
    f.puts File.read("./stuff_to_zip.pdf")
   end
end

Now you can see how much memory the program consumis until done. The method File.read load all bytes of file in memory. Lets see other implementation.

Thread.new do
  loop do
    print "\r memory: %d MB" % "#{`ps -o rss= -p #{Process.pid}`.to_i/1024}\t"
  end
end


Zip::File.open('./compactados.zip', create: true) do |zip|
	10.times do |i|
		zip.get_output_stream("./copy_#{i}.pdf") do |f| 
			input = File.new("./copy_#{i}.pdf")
			while !input.eof?
				f.puts(input.gets)
			end
		end
	end
end
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

Tailwind CSS for Beginners: From Zero to Your First Component

muhammadfarhan.dev - Jul 21

MCP Is the USB-C of AI. So Why Are You Plugging Everything In?

Ken W. Algerverified - Jun 10

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

Web "Hello World" in Ruby without RoR!

luiz filipe neves - Aug 3
chevron_left
141 Points3 Badges
2Posts
0Comments
Software Engenier

Related Jobs

View all jobs →

Commenters (This Week)

4 comments
3 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!