Created
February 2, 2020 14:52
-
-
Save tenebrousedge/fb3e53f86acd0fa8691197a612f2e741 to your computer and use it in GitHub Desktop.
Iterable Example -- Exercism "Protein Translation" solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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