Pregunta

If the first words of the line (one or more) are all in CAPs, I would like to replace those words with the capitalized words (using ruby's .capitalize). For e.g. "FOO BAR" to "Foo Bar"

I tried the following:

line.gsub!(/^([A-Z ]+)/, '\1'.capitalize)

and

line.gsub!(/^([A-Z ]+)/, "\\1".capitalize)

which both did not work. Is there a way to do this?

¿Fue útil?

Solución

Try:

line.gsub!(/^([A-Z ]+)/) { |w| w.capitalize }

In IRB:

require 'active_support'
'FOO bar'.gsub(/^[A-Z]+/) { |w| w.capitalize }
 => "Foo bar" 

or the OP's version:

'FOO bar'.gsub!(/^([A-Z ]+)/) { |w| w.capitalize }
 => "Foo bar" 

For the first two words, this is quick and dirty:

'FOO BAR'.gsub!(/^([A-Z ]+ [A-Z]+)/) { |w| w.capitalize }
 => "Foo bar" 

You can get a little prettier using:

'FOO BAR'.gsub!(/^((?<word>[A-Z]+) \g<word>)/) { |w| w.capitalize }
 => "Foo bar" 

Of course, using the ! version of gsub on a fixed string won't do anything useful.


The OP added additional constraints:

require 'active_support'

line = 'AFOO BFOO CFOO DFOO e f g'
words = line[/^(?:[A-Z]+ )+/].split.map{ |w| w.capitalize } # => ["Afoo", "Bfoo", "Cfoo", "Dfoo"] 
[words,line.split[words.size..-1]].join(' ')                # => "Afoo Bfoo Cfoo Dfoo e f g" 

Otros consejos

You want to capitalize all words in line, correct? Try String#scan instead:

line.scan(/\w+|\W+/).map(&:capitalize).join

I'm no Ruby programmer, but I can see that you're calling capitalize on the string \1, which of course is just \1 again. You will want to look for something similar to PHP's preg_replace_callback that will allow you to run regex matches through a function - in this case, capitalize.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top