N
Nate Wiger
Hi all, I'm trying to port some Perl code to Ruby as part of learning
the language. This code is part of a script called "untar", which is a
simple suffix-based wrapper around unzip/cpio/gunzip/tar/etc.
It starts with suffix to command maps:
zip = {
'gz' => 'gunzip -c',
'Z' => 'uncompress -c',
'zip' => 'unzip',
'bz2' => 'bunzip2 -c'
}
I then want to loop over all files specified, and check if the suffix
matches. If so, I want to strip it and set the proper command. My first
attempt was this:
ARGV.each do |file|
zip.each do |suf, cmd|
if file.sub!(%r{\.#{suf}$}, '')
untar = cmd
break
end
end
# ... more code
end
But sub! always returns nil, even when it succeeds (in Perl, it will
return the number of substitutions made, enabling "next if s/\.$suf$//")
So now I have this:
ARGV.each do |file|
zip.each do |suf, cmd|
if (new = file.sub(%r{\.#{suf}$}, '')) != file
unzip = cmd
file = new
break
end
end
# ... more code
end
Which works, but is not so pretty. Any ideas?
-Nate
P.S. This script allows multiple suffices, aka .tar.bz2, .tar.gz, etc,
hence why it needs to loop repeatedly and strip each one (much code is
not shown above)
the language. This code is part of a script called "untar", which is a
simple suffix-based wrapper around unzip/cpio/gunzip/tar/etc.
It starts with suffix to command maps:
zip = {
'gz' => 'gunzip -c',
'Z' => 'uncompress -c',
'zip' => 'unzip',
'bz2' => 'bunzip2 -c'
}
I then want to loop over all files specified, and check if the suffix
matches. If so, I want to strip it and set the proper command. My first
attempt was this:
ARGV.each do |file|
zip.each do |suf, cmd|
if file.sub!(%r{\.#{suf}$}, '')
untar = cmd
break
end
end
# ... more code
end
But sub! always returns nil, even when it succeeds (in Perl, it will
return the number of substitutions made, enabling "next if s/\.$suf$//")
So now I have this:
ARGV.each do |file|
zip.each do |suf, cmd|
if (new = file.sub(%r{\.#{suf}$}, '')) != file
unzip = cmd
file = new
break
end
end
# ... more code
end
Which works, but is not so pretty. Any ideas?
-Nate
P.S. This script allows multiple suffices, aka .tar.bz2, .tar.gz, etc,
hence why it needs to loop repeatedly and strip each one (much code is
not shown above)