Forum: Ruby gsub! Exceptions when pattern not found

85d4bafb940991a7bcf1fea053be1fcf?d=identicon&s=25 Damian maq0r (maq0r)
on 2013-11-14 18:48
Hey guys,

I'm fairly new at ruby and still learning, I'm trying to clean up some
text and I'm performing some substitutions.

The text that I get doesn't necessarily have all the patterns, so I
could have a text

A B C D E F G

and I would be applying gsub!("A" , "") or gsub!(/B/, "") However, if I
try gsub!(/Z/, "") I get an exception undefined method gsub on nil
because Z is not part of that text.

Is this expected? I'm familiar with Java and other languages were
substitution on strings just continue if the pattern doesn't match,
never heard of raising an exception because of it.

Definitely a silly question, and I'm sure there's more to it, would love
some input, thanks!!!
23172b6630dc631a134c9bad2fec2a39?d=identicon&s=25 Chris Hulan (Guest)
on 2013-11-14 19:01
(Received via mailing list)
are you chaining the gsub!

the error you indicate sounds to me like you are invoking gsub! on a nil
value,
and I believe gsub! (and other ! methods) return nil when they do not
make
a change.
9a45896e48a382fe5c656b8873e0dfcb?d=identicon&s=25 Stu (Guest)
on 2013-11-14 19:57
(Received via mailing list)
I just tested it and it worked here.

Maybe you want to show your complete function.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (robert_k78)
on 2013-11-14 20:08
(Received via mailing list)
On Thu, Nov 14, 2013 at 6:48 PM, Damian maq0r <lists@ruby-forum.com>
wrote:
> and I would be applying gsub!("A" , "") or gsub!(/B/, "") However, if I
> try gsub!(/Z/, "") I get an exception undefined method gsub on nil
> because Z is not part of that text.
>
> Is this expected? I'm familiar with Java and other languages were
> substitution on strings just continue if the pattern doesn't match,
> never heard of raising an exception because of it.

It's not the substitution that throws the error but the next method
invocation.

> Definitely a silly question, and I'm sure there's more to it, would love
> some input, thanks!!!

The docs are always a good place to look - especially for return values:
http://ruby-doc.org/core-1.9.3/String.html#method-i-gsub-21

irb(main):001:0> "a".gsub! /x/, 'y'
=> nil
irb(main):002:0> "a".gsub! /a/, 'y'
=> "y"

Kind regards

robert
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.