Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
24: Regular Expressions in Ruby
Think of a Regular Expression (RegEx) as a "wanted poster" for text. If you were looking for one specific person, you'd just use their name. But if you're looking for anyone who fits a certain profile—say, someone wearing a red hat, carrying a briefcase, and roughly six feet tall—you describe the pattern. You don't care who the individual is, as long as they match those specific traits.
In Ruby, RegEx does exactly that for your strings. Instead of looking for the exact word "Error", you can look for "any line that starts with a date, followed by the word 'Error', and ends with a number." We aren't searching for a static piece of text; we're searching for a shape.
The Anatomy of a Ruby Pattern
In Ruby, we wrap our patterns in forward slashes: /pattern/. This tells Ruby, "Hey, this isn't a string; it's a Regular Expression object."
Let's look at a real-world scenario. Imagine you're processing a list of product IDs that always look like this: two uppercase letters, a hyphen, and four digits (e.g., TS-1234). Here is how I'd build that "wanted poster":
product_id_pattern = /[A-Z]{2}-\d{4}/
Let's break that down point-by-point:
[A-Z]: This is a character class. It means "any single uppercase letter from A to Z".{2}: This is a quantifier. It says "exactly two of the thing that came right before this".-: This is just a literal hyphen. It must be exactly a hyphen.\d: This is a shorthand for "any digit (0-9)".{4}: Again, a quantifier. "Exactly four digits".
Hunting for Matches
Once you have your pattern, you need to actually use it against a string. I usually lean on two different ways depending on what I need. If I just need a "yes or no" answer, I use the =~ operator.
sku = "TS-1234"
if sku =~ /[A-Z]{2}-\d{4}/
puts "Valid SKU!"
end
The =~ operator returns the index of the first match, or nil if nothing is found. Since nil is "falsy" in Ruby, it works perfectly in an if statement. It's quick, it's clean, and it's what I use 90% of the time for simple validation.
However, if you actually need to extract the data, use the .match method. This returns a MatchData object, which is basically a little treasure chest containing everything the RegEx found.
Capturing the Good Stuff
This is where RegEx gets powerful. By using parentheses (), you can create "capture groups." This is like telling Ruby, "Match the whole pattern, but I specifically want you to remember this one part of it for me."
Let's say you're parsing a log entry: "USER_ID: 502 - Login successful". You want the ID number, but not the rest of the noise.
log_line = "USER_ID: 502 - Login successful"
match_data = log_line.match(/USER_ID: (\d+) -/)
if match_data
user_id = match_data[1] # This grabs the first capture group
puts "Processing user #{user_id}..."
end
I've spent way too many hours of my career staring at complex RegEx strings that looked like a cat walked across a keyboard. My advice? Start small. Build your pattern piece by piece and test it against a few strings before you try to write one massive, "perfect" expression. It'll save you a massive headache.
Replacing Chaos with Order
Finally, there's .gsub (global substitution). This is your go-to tool for cleaning up messy data. You can use RegEx to find patterns and replace them with something else.
Imagine you have a string with inconsistent spacing and you want to normalize it to a single space. Instead of a dozen .strip or .split calls, you can just do this:
messy_text = "Too many spaces here"
clean_text = messy_text.gsub(/\s+/, " ")
# \s means any whitespace, + means "one or more"
puts clean_text # "Too many spaces here"📋 Practical Task
The Server Log Parser
You've been handed a raw log file from a legacy server. Each line follows this format: [YYYY-MM-DD] LEVEL: Message. For example: [2023-10-12] ERROR: Database connection failed.
Your task is to write a Ruby script that processes an array of these log strings. For every line that has a level of "ERROR" or "CRITICAL", you must extract the date and the message and print them in the following format: "Alert: On [date], a critical issue occurred: [message]".
Starter Data:
logs = [
"[2023-11-01] INFO: System boot complete",
"[2023-11-01] ERROR: Disk space low",
"[2023-11-02] DEBUG: Heartbeat sent",
"[2023-11-02] CRITICAL: Kernel panic",
"[2023-11-03] INFO: User logged in"
]
Requirements:
- Use a Regular Expression with capture groups to isolate the date and the message.
- Ensure you only target "ERROR" or "CRITICAL" levels (Hint: use the
|"OR" operator in your RegEx). - Ignore "INFO" and "DEBUG" lines entirely.
There are no comments for now.