Zipping files using the Rubyzip gem

# installation: gem install rubyzip

require 'zip'

# First of all we will change to the /tmp directory
path = '/tmp'
Dir.chdir path

# Then create the files

File.write 'groceries.txt', "# Grocery list\n\n* milk\n* bread\n *eggs"
File.write 'todo.txt', "# Housework\n\n* vacuum bedroom\n* dust wardrobe"
File.write 'sample1.txt', "testing ...\nline 2\n line 3"

# Now to zip the files ...

files = %w(groceries.txt todo.txt sample1.txt)

zipfile = "txt_samples.zip"

Zip::File.open(zipfile, Zip::File::CREATE) do |x|
  files.each {|filename| x.add(filename, File.join(path, filename))}
end


If the file to be zipped is in a buffer:

require 'zip'

Dir.chdir '/tmp'

a = [['groceries.txt', "# Grocery list\n\n* milk\n* bread\n *eggs"],
['todo.txt', "# Housework\n\n* vacuum bedroom\n* dust wardrobe"],
['sample1.txt', "testing ...\nline 2\n line 3"]]

zipfile = "txt_samples.zip"

Zip::File.open(zipfile, Zip::File::CREATE) do |x|

  a.each do |filename, buffer| 
    x.get_output_stream(filename) {|os| os.write buffer }
  end

end

Resources