
You Are Writing Regex Wrong: A Guide to Ruby’s Best Hidden Feature
The "Two Problems" Joke There is an old programmer joke: "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." In most languages (Java, JavaScript), Regex is a pain. It feels like a foreign language bolted onto the code. In Ruby, Regex is a first-class citizen. It isn't just a string you pass to a function; it is a literal object ( /pattern/ ) with superpowers. Here is how to move from "Copy-Pasting StackOverflow" to "Regex Master." Level 1: The Modern Syntax ( match? ) Stop using the "Spaceship operator" ( =~ ). It’s cryptic, it returns an integer (index) or nil, and it sets global variables ( $1 , $2 ) that are hard to debug. Use the boolean method introduced in Ruby 2.4: email = "zil@example.com" # The Old Way (Don't do this) if email =~ /@/ puts "Valid" end # The Ruby Way if email . match? ( /@/ ) puts "Valid" end It’s faster, cleaner, and returns true or false . Level 2: Named Captures (The Game Changer) This is th
Continue reading on Dev.to Webdev
Opens in a new tab

