ruby - Using gsub or sub to replace one character -



ruby - Using gsub or sub to replace one character -

i want replace 3rd character of string upper case counterpart. using gsub or sub causing next error:

"hiiiii".sub!(string[2,1],string[2,1].upcase!) # => hiiiii "hello".gsub!(string[2,1],string[2,1].upcase!) # => hello

while gsub unexpectedly replaced similar characters, sub replaced first occurrence, irrespective of position mention.

can suggest how can create sub work after 3rd character?

you can utilize regular look positive lookbehind this. lookarounds not consume characters in string, assert whether match possible or not.

"hiiiii".sub(/(?<=..)./, &:upcase) # => "hiiiii"

explanation:

(?<= # behind see if there is: . # character except \n . # character except \n ) # end of look-behind . # character except \n

ruby regex string gsub

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -