简体   繁体   中英

How to replace every 4th character of a string using .gsub in Ruby?

Beginner here, obviously. I need to add a sum and a string together and from the product, I have to replace every 4th character with underscore, the end product should look something like this: 160_bws_np8_1a

I think .gsub is the way, but I can find a way to format the first part in .gsub where I have to specify every 4th character.

total = (1..num).sum
final_output = "#{total.to_s}"  + "06bwsmnp851a"
return final_output.gsub(//, "_")

This would work:

s = '12345678901234'
s.gsub(/(...)./, '\1_')
#=> "123_567_901_34"

The regex matches 3 characters ( ... ) that are captured (parentheses) followed by another character ( . ). Each match is replaced by the first capture ( \1 ) and a literal underscore ( _ ).

s = "12345678901234"

Here are two ways to do that. Both return

"123_567_901_34"

Match every four-character substring and replace the match with the first three characters of the match followed by an underscore

s.gsub(/.{4}/) { |s| s[0,3] << '_' }

Chain the enumerator s.gsub(/./) to Enumerator#with_index and replace every fourth character with an underscore

s.gsub(/./).with_index { |c,i| i%4 == 3 ? '_' : c }

See the form of String#gsub that takes a single argument and no block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM