DEV Community

Scott Watermasysk
Scott Watermasysk

Posted on • Originally published at scottw.com on

3

Do Not Overthink Ruby

I was reading through the Ruby regex docs trying to figure out how to iterate over a string and replace all the matches of a particular pattern.

The tricky part is the matches are not one to one (not just a find and replace). I tried a bunch of different things and then started wishing gsub took a block….turns out it already does this.

Example:

"1234".gsub(/\d/) {|i| i.to_i * 2} # 2468

Even better, it handles all substitution

"Square this number: 5".gsub(/\d/) {|i| i.to_i * i_to_i}
# Square this number: 25

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay