Do Not Overthink Ruby

Originally published at scottw.com on Mar 21, 2019 ・1 min read

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

DISCUSS
Classic DEV Post from Jul 3 '18

Can't get engineering interviews? Try the side door.

If you're struggling to get engineering interviews at startups, consider trying other ways to get your foot in the door. Do more than just submit an application.

Boostrapped Founder

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️