[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Easy way to check is sub!() succeeds?

Gavin Kistner

10/20/2006 7:02:00 PM

> But sub! always returns nil, even when it succeeds (in Perl, it will
> return the number of substitutions made, enabling "next if
> s/\.$suf$//")

Er, no it doesn't.

irb(main):001:0> s="aaabbb"
=> "aaabbb"
irb(main):002:0> s.sub!(/a+/,'')
=> "bbb"
irb(main):003:0> s.sub!(/zzz/,'')
=> nil

C:\>ri String.sub!
------------------------------------------------------------ String#sub!
str.sub!(pattern, replacement) => str or nil
str.sub!(pattern) {|match| block } => str or nil
------------------------------------------------------------------------
Performs the substitutions of +String#sub+ in place, returning
_str_, or +nil+ if no substitutions were performed.

1 Answer

Nate Wiger

10/20/2006 9:57:00 PM

0

Gavin Kistner wrote:
>> But sub! always returns nil, even when it succeeds (in Perl, it will
>> return the number of substitutions made, enabling "next if
>> s/\.$suf$//")
>
> Er, no it doesn't.
>
> irb(main):001:0> s="aaabbb"
> => "aaabbb"
> irb(main):002:0> s.sub!(/a+/,'')
> => "bbb"
> irb(main):003:0> s.sub!(/zzz/,'')
> => nil

Ok, that makes more sense. Turns out I was upsetting Ruby's
scoping/aliasing. Eventually I got an error "Can't modify frozen
string", which tipped me off. Now I have:

ARGV.each do |file|
path = file.dup # copy to tweak
zip.each do |suf, cmd|
if path.sub!(%r{\.#{suf}$}, '')

And everything works ok. Seems like a loop w/i a loop thing? Anyways,
thanks for the sub!() ptr.

-Nate