Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
Zlib::Deflate.new
static VALUE
rb_deflate_initialize(int argc, VALUE *argv, VALUE obj)
{
struct zstream *z;
VALUE level, wbits, memlevel, strategy;
int err;
rb_scan_args(argc, argv, "04", &level, &wbits, &memlevel, &strategy);
TypedData_Get_Struct(obj, struct zstream, &zstream_data_type, z);
err = deflateInit2(&z->stream, ARG_LEVEL(level), Z_DEFLATED,
ARG_WBITS(wbits), ARG_MEMLEVEL(memlevel),
ARG_STRATEGY(strategy));
if (err != Z_OK) {
raise_zlib_error(err, z->stream.msg);
}
ZSTREAM_READY(z);
return obj;
}
Creates a new deflate stream for compression. If a given argument is nil, the default value of that argument is used.
The level sets the compression level for the deflate stream between 0 (no compression) and 9 (best compression). The following constants have been defined to make code more readable:
See www.zlib.net/manual.html#Constants for further information.
The window_bits sets the size of the history buffer and should be between 8 and 15. Larger values of this parameter result in better compression at the expense of memory usage.
The mem_level specifies how much memory should be allocated for the internal compression state. 1 uses minimum memory but is slow and reduces compression ratio while 9 uses maximum memory for optimal speed. The default value is 8. Two constants are defined:
The strategy sets the deflate compression strategy. The following strategies are available:
Zlib::DEFAULT_STRATEGY-
For normal data
Zlib::FILTERED-
For data produced by a filter or predictor
Zlib::FIXED-
Prevents dynamic Huffman codes
Zlib::HUFFMAN_ONLY-
Prevents string matching
Zlib::RLE-
Designed for better compression of PNG image data
See the constants for further description.
Examples
Basic
open "compressed.file", "w+" do |io| io << Zlib::Deflate.new.deflate(File.read("big.file")) end
Custom compression
open "compressed.file", "w+" do |compressed_io| deflate = Zlib::Deflate.new(Zlib::BEST_COMPRESSION, Zlib::MAX_WBITS, Zlib::MAX_MEM_LEVEL, Zlib::HUFFMAN_ONLY) begin open "big.file" do |big_io| until big_io.eof? do compressed_io << zd.deflate(big_io.read(16384)) end end ensure deflate.close end end
While this example will work, for best optimization review the flags for your specific time, memory usage and output space requirements.