Skip to content

Ruby: Create Zip files

In Ruby, you can use the zip library to create zip files. Here’s an example of how you can create a zip file containing multiple files:

First, make sure you have the zip gem installed. You can install it via RubyGems:

gem install rubyzip

Now, here’s an example that demonstrates how to create a zip file containing multiple files:

require 'zip'

# Array of file paths to include in the zip
files_to_zip = ['file1.txt', 'file2.txt', 'folder/file3.txt']

# Name for the resulting zip file
zip_file_name = 'my_archive.zip'

Zip::File.open(zip_file_name, Zip::File::CREATE) do |zipfile|
  files_to_zip.each do |file|
    # Add files to the zip one by one
    zipfile.add(file, file)
  end
end

puts "Zip file created: #{zip_file_name}"

In this example:

  1. files_to_zip is an array containing paths to the files you want to include in the zip. Adjust it according to your requirements.
  2. zip_file_name is the name you want to give to your resulting zip file.

The Zip::File.open block creates the zip file (my_archive.zip in this case) and iterates through each file in the files_to_zip array. It adds each file to the zip using zipfile.add(file, file).

Make sure to provide correct file paths relative to the location of your script or use absolute paths for the files you want to zip.

This code will create a zip file named my_archive.zip containing the specified files. Adjust the file paths and names according to your needs.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments