---
title: Ruby's gsub With A Block
teaser:
tags: web,ruby
author: Dan Croak
published_on: 2009-09-08
---

Ruby's `gsub` can take a block:

    "10 comments".gsub(/ (.+)/) do |words|
      " <div class="superstyle">#{words.lstrip}</div>"
    end

    # "10 <div class="superstyle">comments</div>"

The block parameter is the match. This style offers and opportunity to give it
an intention-revealing name instead of `$1`.

I expected `$1` to be the first block parameter, `$2` to be the second block
parameter, etc., but I have only been able to get one block variable.
