Skip to Main Content

Easy lexical replacement with Ruby's gsub method

gsub(pattern, hash) → new_str

In Ruby's String#gsub method, if the second argument is a Hash, and the matched text is one of its keys, the corresponding hash value is the replacement string.

ALTS = { "cat" => "man", "hat" => "mirror" }
"The cat in the hat".gsub(/.at/, ALTS)
=> "The man in the mirror"

See the Ruby docs for more.

 

Most RecentRSS

ArchiveRSS

March 2016 (1)
January 2016 (1)
September 2015 (1)
May 2015 (1)
April 2015 (1)
March 2015 (1)
February 2015 (2)
January 2015 (5)
September 2014 (2)
August 2014 (4)
July 2014 (1)
March 2014 (1)
November 2013 (3)
September 2013 (3)
July 2013 (6)
June 2013 (1)
May 2013 (1)
March 2013 (2)
February 2013 (3)
January 2013 (4)