Do Not Overthink Ruby

twitter logo github logo Originally published at scottw.com on ・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

twitter logo DISCUSS
Classic DEV Post from May 1

Build a 💣 Bomb-Diggity Technical Presentation (🎤 Mic Drop Optional)

The steps and process behind building a great technical presentation.

Scott Watermasysk profile image
Boostrapped Founder

It's like Medium meets Reddit, but specifically for software developers. Sign up now ❤️

(And we're open source!)