Gsub! Exceptions when pattern not found

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!!!

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.

I just tested it and it worked here.

Maybe you want to show your complete function.

On Thu, Nov 14, 2013 at 6:48 PM, Damian maq0r [email protected]
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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs