Skip to content

Instantly share code, notes, and snippets.

@durrellchamorro
Created March 12, 2016 01:09
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 durrellchamorro/ffae838d2f29cf4ca886 to your computer and use it in GitHub Desktop.
Save durrellchamorro/ffae838d2f29cf4ca886 to your computer and use it in GitHub Desktop.
Trinary
class Trinary
def initialize(string)
@trinary_number = string
end
def to_decimal
return 0 if contains_any_non_digit?
numbers_paired_with_powers.map do |pair|
pair[0].to_i * 3**pair[1]
end.inject(:+)
end
private
def contains_any_non_digit?
@trinary_number =~ /\D/
end
def numbers_paired_with_powers
powers = 0..@trinary_number.size - 1
@trinary_number.chars.zip(powers.to_a.reverse)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment