binary.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Binary
  VERSION = 1

  def initialize(number)
    unless /^[01]+$/.match(number)
      raise ArgumentError, "Invalid binary string"
    end

    @number = number
  end

  def to_decimal()
    # Reverse the digits
    reverse_digits = @number.reverse.split('').map(&:to_i)
    # Multiply each by the respective power of two
    reverse_digits.each_with_index.inject(0) { |sum,(n,i)| sum + (n * 2**i) }
  end
end

Comments

Fix bad variable name, and use unless

helenst commented 18 March 2016 at 21:34 UTC

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