Last Updated: February 25, 2016
·
1.71K
· amydoesntlai

Ruby gsub with a hash or block

Fun Ruby fact: you can gsub with a block or hash.

After defining a hash,

amino_acid_hash = { 'A' => 'Ala', 'R' => 'Arg', 'N' => 'Asn' } # etc.

you can pass the hash name as the second argument to gsub, and it will substitute in the hash values.

"R232A".gsub(/[A-Z]/, amino_acid_hash)
=> "Arg232Ala"

You can also pass a block:

"12345".gsub(/\d/) { |n| n.to_i*2 }
=> "246810"