Skip to content

Commit

Permalink
binary: Add error handling
Browse files Browse the repository at this point in the history
This adds some additional test cases to clarify the behavior around
the conversion of valid/invalid binary input.

See exercism/problem-specifications#95
  • Loading branch information
kytrinyx committed Jun 20, 2015
1 parent b1dba08 commit bb85b9e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
23 changes: 19 additions & 4 deletions binary/binary_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
require_relative 'binary'

class BinaryTest < Minitest::Test
def test_binary_0_is_decimal_0
assert_equal 0, Binary.new('0').to_decimal
end

def test_binary_1_is_decimal_1
assert_equal 1, Binary.new('1').to_decimal
end
Expand Down Expand Up @@ -38,13 +42,24 @@ def test_binary_10001101000_is_decimal_1128
assert_equal 1128, Binary.new('10001101000').to_decimal
end

def test_invalid_binary_string_is_decimal_0
def test_binary_ignores_leading_zeros
skip
assert_equal 31, Binary.new('000011111').to_decimal
end

def test_invalid_binary_numbers_raise_an_error
skip
assert_equal 0, Binary.new('carrot123').to_decimal
%w(012 10nope nope10).each do |input|
assert_raises ArgumentError do
Binary.new(input)
end
end
end

def test_invalid_binary_numeric_string_is_decimal_0
# This test is for the sake of people providing feedback, so they
# know which version of the exercise you are solving.
def test_bookkeeping
skip
assert_equal 0, Binary.new('123').to_decimal
assert_equal 1, Binary::VERSION
end
end
16 changes: 10 additions & 6 deletions binary/example.rb
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
class Binary
VERSION = 1

attr_reader :digits
def initialize(decimal)
@digits = normalize(decimal).reverse.chars.collect(&:to_i)
def initialize(s)
raise ArgumentError.new("invalid binary input #{s}") unless valid?(s)

@digits = s.chars.reverse.collect(&:to_i)
end

def to_decimal
digits.each_with_index.inject(0) do |decimal, (digit, index)|
decimal + digit * 2**index
digits.each_with_index.inject(0) do |decimal, (digit, i)|
decimal + digit * 2**i
end
end

private

def normalize(string)
string.match(/[^01]/) ? '0' : string
def valid?(s)
s.chars.all? {|char| ['0', '1'].include?(char)}
end
end

0 comments on commit bb85b9e

Please sign in to comment.