官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 桂阳县| 新沂市| 沭阳县| 东兰县| 微博| 永清县| 华池县| 扶绥县| 出国| 佛坪县| 泗水县| 图们市| 涿州市| 英超| 姚安县| 昭觉县| 凌源市| 泾川县| 涪陵区| 分宜县| 湘阴县| 金寨县| 广元市| 达尔| 海丰县| 沙坪坝区| 资源县| 松溪县| 平乡县| 长治市| 雷波县| 吐鲁番市| 宿州市| 兰考县| 诏安县| 长岛县| 福鼎市| 湘西| 勐海县| 门源| 东乡族自治县|