Ruby's gsub With A Block

Dan Croak

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.

About thoughtbot

We've been helping engineering teams deliver exceptional products for over 20 years. Our designers, developers, and product managers work closely with teams to solve your toughest software challenges through collaborative design and development. Learn more about us.