Change replacement case

I have the following: text.gsub(/(lower) (upper)/, '\1 \2')

Can I make a simple \2uppercase substitution ?

Sort of: sed -e 's/\(abc\)/\U\1/'

Is this possible in Ruby?

+5
source share
3 answers

see gsub doc:

str.gsub (pattern) {| match | block} → new_str

In the block form, the current matching string is passed as a parameter, and variables such as $ 1, $ 2, $ `, $ &, and $ will be set accordingly. The value returned by the block will be replaced with a match for each call.

"a lower upper b".gsub(/(lower) (upper)/){|s| $1 + " " + $2.upcase}

+6
source

gsubaccepts a block argument that is triggered for each match, passing it as a parameter - so you can do whatever you like! For example, to smooth out every word in a line:

"ruby blocks are pretty awesome".gsub(/\w+/) do |match|
  match.capitalize
end
#=> "Ruby Blocks Are Pretty Awesome"
+2

Ruby - , , , ? $n bock:

new_text = text.gsub(/(lower) (upper)/){
    "#{$1} #{$2.upcase}"
}

Update
It looks like Brandon beat me up to 8 minutes :) It's almost the same as AFAIK

+2
source

All Articles