LoginSignup
5
6

More than 5 years have passed since last update.

rubyzipでZip内のファイル名を変更する

Posted at

例えばzipファイル内のfoo.txtをbar.txtにリネームするには次のようにする。

require "zip"

Zip::File.open(zip_path) do |zip_file|
  entry = zip_file.find_entry("foo.txt") # Zip::Entry
  zip_file.rename(entry, "bar.txt")
end

ループで回して一括で連番にしたいときには次のようにする。

require "zip"

Zip::File.open(zip_path) do |zip_file|
  # Zip::File#entriesはEnumerableなZip::EntrySetを返す
  zip_file.entries.sort_by(&:name).each.with_index(1) do |entry, n|
    new_name = "#{n}.txt"
    zip_file.rename(entry, new_name)
  end
end

rubyzip 1.1.7で確認した。1.xと0.xとでAPIが変わっているので要注意。

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6