I am learning Ruby and thought of making a Binary->Decimal converter. It gets a binary string and converts to decimal equivalent. Is there a way to keep track of the current iteration step in ruby so that the variable ‘x’ can be removed?
def convert(binary_string)
decimal_equivalent = 0
x=0
binary_string.reverse.each_char do |binary|
decimal_equivalent += binary.to_i * (2 ** x)
x+=1
end
return decimal_equivalent
end
Yes, by using the very powerful enumerator library:
Incidentally, you may be interested in
Array#pack, andString#unpack. They have support for bit strings. Also, an even easier way to get this result is to use#to_i, e.g."101".to_i(2) #=> 5