binary.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Convert a binary number string (e.g. '101010') to decimal equivalent
class Binary
  VERSION = 1

  def initialize(number)
    raise ArgumentError, 'Invalid binary string' unless /^[01]+$/ =~ number

    @number = number
  end

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

@tachyons, @rbndickson, and @jdhmtl think this looks great

Comments

Learned of a better solution to this when doing the equivalent Scala exercise. Also rubocopped it.

helenst commented 13 May 2016 at 08:54 UTC

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