Regex and gsub quest

Hi

Another quick question (at the risk of being the person who asks for help on
adding 2+2 at the alt.math.relatavistic.astrophysics group):

I am trying to search thru a file (arrays of words and sentence fragments),
and replace the commas with a space.
Why doesn't the code below work : (other than an incorrect regex for comma)

a = ["hi,there", "jot this note down", "may i,use the, car"]
a.each do |x| x.gsub(/\,/ , " ") end

- the general method of
array.each do {|e| e.gsub(pattern, replacement)} doesn't work?

Thanks again

CLS

gsub is not a destructive method, meaning every time you call it it
returns a new string. You should use gsub! mehtod which makes changes
in place.

Kent.

···

On 6/29/05, Charles L. Snyder <csnyder1@kc.rr.com> wrote:

Hi

Another quick question (at the risk of being the person who asks for help on
adding 2+2 at the alt.math.relatavistic.astrophysics group):

I am trying to search thru a file (arrays of words and sentence fragments),
and replace the commas with a space.
Why doesn't the code below work : (other than an incorrect regex for comma)

a = ["hi,there", "jot this note down", "may i,use the, car"]
a.each do |x| x.gsub(/\,/ , " ") end

- the general method of
array.each do {|e| e.gsub(pattern, replacement)} doesn't work?

Thanks again

CLS

Charles L. Snyder wrote:

- the general method of
array.each do {|e| e.gsub(pattern, replacement)} doesn't work?

Because you first substitute and then throw away the result.

You can either create a new array with

new_array = array.map { |e| e.gsub(pattern, replacement) }

or substitute the strings in place with

array.each { |e| e.gsub!(pattern, replacement) }

You can do the same to the array of course:

array.map! { |e| e.gsub(pattern, replacement) }

But be careful, if you use !-methods, they can have unintended consequences.

···

--
Florian Frank

As well as using gsub! to see any result in your case,
you should not prepend the comma with a backslash, the
comma has no special meaning.

Last, never play with regexes without irb and your favorite ShowRE !

def showRE(a,re)
   if a =~ re
     res = "#{$`}<<#{$&}>>#{$'}\n"
     res += "1: #$1\n"
     res += "2: #$2\n"
     res += "3: #$3\n"
     res += "4: #$4\n"
     res += "5: #$5\n"
     res += "6: #$6\n"
     res += "7: #$7\n"
     res += "8: #$8\n"
     res += "9: #$9\n"
   else
     "no match"
   end
end

puts showRE( "hi,there", /,/ )

···

On Wed, 29 Jun 2005 16:12:13 +0200, Kent Sibilev <ksruby@gmail.com> wrote:

Why doesn't the code below work : (other than an incorrect regex for comma)

a = ["hi,there", "jot this note down", "may i,use the, car"]
a.each do |x| x.gsub(/\,/ , " ") end

--
Katarina