Ruby's gsub With A Block

Ruby’s gsub can take a block:

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

# "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.


Hound automatically reviews Ruby, JavaScript, CoffeeScript, and SCSS code in your GitHub pull requests and comments on style violations. It is free for open source repos and $12/month per private repo.