Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Scott Watermasysk
Scott Watermasysk

Posted on • Originally published atscottw.com on

     

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 wishinggsub 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Boostrapped Founder. In to Ruby, Rails, JavaScript, VSCode, React, Tailwind, and more.
  • Location
    New Jersey
  • Work
    Founder at KickoffLabs
  • Joined

More fromScott Watermasysk

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp