Skip to content

Instantly share code, notes, and snippets.

@shepmaster
Forked from alekst/dna.rb
Last active December 22, 2015 11:28
Show Gist options
  • Save shepmaster/6465405 to your computer and use it in GitHub Desktop.
Save shepmaster/6465405 to your computer and use it in GitHub Desktop.
class DNATest < MiniTest::Unit::TestCase
# You don't have to put your classes inside of the test case, but it
# doesn't hurt for these examples
class DNA
def initialize(string)
@string = string
# You can provide a default value for hashes. This also avoids
# hardcoding the letters here.
@counts = Hash.new(0)
dna_validation
end
def count(element)
# Renamed to be active, and take a param. There's no reason to
# save this as an instance variable, as it isn't "long-term"
# state.
validate_element(element)
# No reason to sort the letters, as it shouldn't change the
# result, and only will take more time. It's also confusing to
# someone else reading it, as they have to decide if it's
# important. No reason to be an instance variable.
@string.chars.count(element)
# @string.chars /could/ be saved, as it will always be the same,
# and /might/ save some processing time.
end
def nucleotide_counts
# Ditto sorting and saving the value, especially as it's used
# in multiple places.
nucleotides = @string.chars.sort
nucleotides.each do |nucleotide|
@counts[nucleotide] += 1
end
@counts
# This instance variable will be saved between multiple calls to
# this method, and continue to accumulate. I'd expect the answer
# to be the same each time.
end
def dna_validation
# You don't have to return a value. This can be written as just
return if @string.empty?
raise ArgumentError, "DNA is not RNA" if @string.include?('U')
raise ArgumentError, "This is not a DNA" unless @string.match(/[ACGT]/)
end
def validate_element(element)
raise ArgumentError, "There are no such nucleotides" unless element.match(/[ACGTU]/)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment