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

Time:07-17

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(//, "_")

CodePudding user response:

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 (_).

CodePudding user response:

Match every four characters and replace the match with the first three characters matched followed by an underscore:

'12345678901234'.gsub(/.{4}/) { |s| s[0,3] << '_' }
  #=> "123_567_901_34"
  • Related