Ruby's gsub With A Block

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.

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.