Zulhilmi Zainudin Zulhilmi Zainudin - 4 months ago 30
Ruby Question

How to only mask middle part of Ruby string?

I have this:

phone = "+60123453180"
p = phone.gsub!(/(?=...).(?=....)/, '*')
=> "********3180"


How to only mask
345
and return
+6012***3180
?

Answer
phone = "+60123453180"
phone.tap { |p| p[5...8] = "****" }
#⇒ "+6012****3180"

Play with 5...8 range to modify an amount of symbols to be substituted.

NB Your original code modified the phone inplace, hence the code above also modifies it inplace.

To keep the original value intact, one might use dup:

phone.dup.tap { |p| p[5...8] = "****" }
#⇒ "+6012****3180"
phone
#⇒ "+60123453180"
Comments