gsub(/\s*$/, "") doubling string

P

Paul Rubel

Hello,
I recently downloaded ruby 1.8.0 p3, (2003-06-23) [i686-linux], and
tried it on some code that chopped trailing spaces from a string using
gsub(/\s*$/, ""). I'm seeing some odd behavior and was hoping someone
could shed some light on what's happening.

In 1.6.7 the code above did what I expected. However, in 1.8.0p3 it
seems to double the string if the string doesn't end in a space.

#does what I expected in 1.6 and 1.8
irb(main):004:0> " TEST ".gsub(/\s*$/, "")
=> " TEST"

# very odd (at least to me) in 1.8.0p3
irb(main):005:0> " TEST .".gsub(/\s*$/, "")
=> " TEST . TEST ."

Where does this repeat come from? If I change the * to a + it fixes my
problem but I was hoping someone could help explain why it's happening.

While looking into this I've noticed that there seems to be something
special about 2 repeats.

irb(main):002:0> " string ".gsub(/\s*$/, 'P')
" stringPP"

Regardless of how many trailing spaces I add two Ps are always
appended. It seems that one matches all the spaces and then one matches
the zero length string that's the end itself since a string without
trailing spaces puts in one P. Is the $ getting used twice in this
match?

I'd appreciate any explanations or help.
thank you,
Paul
 
K

Kurt M. Dresner

I don't know what the problem is, but you should probably be using
gsub(/\s+$/,'') anyway :eek:)

-Kurt
 
Y

Yukihiro Matsumoto

Hi,

In message "Re: gsub(/\s*$/, "") doubling string"

|P> # very odd (at least to me) in 1.8.0p3
|P> irb(main):005:0> " TEST .".gsub(/\s*$/, "")
|P> => " TEST . TEST ."
|
| Can you try this

Thank you for the fix, Guy. And thank you for finding a bug, Paul.

|P> irb(main):002:0> " string ".gsub(/\s*$/, 'P')
|P> " stringPP"
|
| this is normal

The first try replaces all trailing spaces with "P", then second try
replaces empty at the end of string with "P".

matz.
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top