Easy way to check is sub!() succeeds?

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top