trinary.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
# Convert a trinary number string (e.g. '102012') to decimal equivalent
class Trinary
  def initialize(number)
    @number = number
  end

  def to_decimal
    return 0 unless /^[012]+$/ =~ @number

    # Shift the accumulated value along one place and add this digit
    @number.chars.map(&:to_i).inject(0) { |a, e| a * 3 + e }
  end
end

Comments


You're not logged in right now. Please login via GitHub to comment