GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS

Written by thoughtbot

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.