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

Viewed 108

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

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.

Related