Sha256: 8171e4054e5787067820017a0b5359ce1544df567427f532dc02acf49c3fa6cc

Contents?: true

Size: 658 Bytes

Versions: 396

Compression:

Stored size: 658 Bytes

Contents

class Hexadecimal
  BASE = 16

  attr_reader :digits
  def initialize(decimal)
    @digits = decimal.reverse.chars
  end

  def to_decimal
    return 0 unless valid?

    decimal = 0
    digits.each_with_index do |digit, index|
      decimal += values[digit] * BASE**index
    end
    decimal
  end

  def valid?
    !digits.to_a.join('')[/[^0-9a-f]/, 0]
  end

  def values
    {
      '0' => 0,
      '1' => 1,
      '2' => 2,
      '3' => 3,
      '4' => 4,
      '5' => 5,
      '6' => 6,
      '7' => 7,
      '8' => 8,
      '9' => 9,
      'a' => 10,
      'b' => 11,
      'c' => 12,
      'd' => 13,
      'e' => 14,
      'f' => 15
    }
  end
end

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.179 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.178 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.177 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.176 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.175 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.174 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.173 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.172 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.171 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.170 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.169 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.167 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.166 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.165 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.164 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.163 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.162 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.161 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb
trackler-2.2.1.160 tracks/ruby/exercises/hexadecimal/.meta/solutions/hexadecimal.rb