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"
Written by Amy Lai
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#