diff --git a/binary/binary_test.rb b/binary/binary_test.rb index 03ee5917c9..652eace6ff 100755 --- a/binary/binary_test.rb +++ b/binary/binary_test.rb @@ -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 @@ -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 diff --git a/binary/example.rb b/binary/example.rb index 77b2a3a815..9460a1ba1c 100644 --- a/binary/example.rb +++ b/binary/example.rb @@ -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