Skip to content

Instantly share code, notes, and snippets.

@tenebrousedge
Created February 2, 2020 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tenebrousedge/fb3e53f86acd0fa8691197a612f2e741 to your computer and use it in GitHub Desktop.
Save tenebrousedge/fb3e53f86acd0fa8691197a612f2e741 to your computer and use it in GitHub Desktop.
Iterable Example -- Exercism "Protein Translation" solution
require "string_scanner"
module ProteinTranslation
class Polypeptide
alias Codon = String
include Iterator(Codon)
CODONS = {
/AUG/ => "Methionine",
/UUU|UUC/ => "Phenylalanine",
/UUA|UUG/ => "Leucine",
/UCU|UCC|UCA|UCG/ => "Serine",
/UAU|UAC/ => "Tyrosine",
/UGU|UGC/ => "Cysteine",
/UGG/ => "Tryptophan",
}
STOP_CODONS = "UAG|UAA|UGA"
BASES = "UAGC"
POLYPEPTIDE = /[#{BASES}]+(?=#{STOP_CODONS})?/
def initialize(rna)
@scanner = StringScanner.new(rna.sub(/(#{STOP_CODONS}).*/, ""))
end
def next
@scanner.scan(/[#{BASES}]{3}/).try(&->find_codon(String)) || stop
end
private def find_codon(c)
CODONS.find { |k, _| k =~ c }.try &.last
end
end
def self.proteins(rna)
Polypeptide.new(rna).to_a
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment