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) if not /^[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_numbers.each_with_index.inject(0) { |sum,(n,i)| sum + (n * 2**i) } end end |

class Binary
VERSION = 1
def initialize(number)
if not /^[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_numbers.each_with_index.inject(0) { |sum,(n,i)| sum + (n * 2**i) }
end
end

@Vladcz thinks this looks great

## Comments

Hi, you have really nice and clean solution, but did your test really pass? You should probably get NoMethodError for nil class at line 16. Also more ruby way would be using unless instead of if not.

Hmm, I renamed the variable to reverse_digits after my last run of the tests - is that what you meant? It passes now I have corrected that. I've also changed it to use

`unless`

. Thanks, always looking for more ruby-like ways to do things!You're not logged in right now. Please login via GitHub to comment