- Comprehensive Ruby Programming
- Jordan Hudgens
- 445字
- 2025-04-04 18:58:15
Becoming a block head
As great as gsub can be by itself, it can become even more powerful when used in conjunction with blocks. Blocks are incredibly useful tools that we'll be using throughout the rest of this book, so we will go into more detail on exactly what blocks are later on. For now, just think of blocks as being tools that allow you to extend the functionality of a method. Let's take a look at another example of how to use gsub, but this time we're going to pass in a block:
content = "# My Great Headline"
content.gsub(/^.*#.*/) { |heading| "<h1>#{heading[2..-1]}</h1>" }
Woah, I know that this code may look weird, don't let it scare you away; let's analyze every process that is going on, along with what the code does. This is the code that parses the markdown language. Markdown is a helpful language that allows users to add styles to text files with some basic symbols. For example, passing in the # character tells markdown that the text following the hash symbol should be a headline. So our code looks for the hashtag symbol and wraps the entire line of code with the <h1> tags so it can be rendered in a web browser. Now that you know what markdown is, let's analyze the code, bit by bit.
The /^.*#.*/ code is the argument passed to the gsub method. This weird set of characters are called regular expressions. We have dedicated an entire chapter to regular expressions later on in the book. For now, just know that regular expressions are coding tools that allow you to match string-based patterns. In the case of our example, we're matching all lines that start with the # character.
So what happens next? Now that the regular expression matches the line of text, the gsub method moves down to the curly brackets. In Ruby, a block can be defined by curly brackets (as in the preceding example) or with the do and end keywords. Inside of the curly brackets we first define a block variable inside of the pipes. This block variable can be called pretty much anything; for our example, I used the heading variable name. The block variable is going to represent every match that the gsub method brings us. If we were working with a file worth of text, the block variable would represent each time the regular expression was matched. For our basic example, this will be the full content variable. From there, we use string interpolation to wrap the entire match in the <h1></h1> tags. And our job is done. The end result will be the <h1>My Great Headline</h1> output.