# Easy way to check is sub!() succeeds?

**URL:** <https://www.ruby-forum.com/t/easy-way-to-check-is-sub-succeeds/73042>\
**Category:** Ruby\
**Created:** [October 20, 2006, 8:41pm UTC](https://www.ruby-forum.com/t/easy-way-to-check-is-sub-succeeds/73042 "2006-10-20T20:41:11Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![nwiger](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/dbc845/32.png) [@nwiger](https://www.ruby-forum.com/u/nwiger)\
**Post date:** [October 20, 2006, 8:41pm UTC](https://www.ruby-forum.com/t/easy-way-to-check-is-sub-succeeds/73042/1 "2006-10-20T20:41:11Z")

</div>

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)
