views:

391

answers:

2

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
+1  A: 
binary_string.reverse.chars.each_with_index do |binary, i|
  decimal_equivalent += binary.to_i * (2 ** i)
end

Or on versions older than 1.8.7:

binary_string.reverse.split(//).each_with_index do |binary, i|
  decimal_equivalent += binary.to_i * (2 ** i)
end
Brian Campbell
it says undefined method chars for "0":String
kunjaan
What version of ruby are you using? "ruby --version" to find out
Brian Campbell
It looks like String#chars was added in 1.8.7. I'll update my answer with a version that works with earlier versions.
Brian Campbell
Ah. As Logan points out, using the enumerator library gives you enum_for(:each_char), which is the equivalent of the String#chars method introduced in 1.8.7.
Brian Campbell
+4  A: 

Yes, by using the very powerful enumerator library:

require 'enumerator'
def convert(binary_string)
  decimal_equivalent = 0
  binary_string.reverse.enum_for(:each_char).each_with_index do |binary, i|
    decimal_equivalent += binary.to_i * (2 ** i)
  end
  return decimal_equivalent
end

Incidentally, you may be interested in Array#pack, and String#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

Logan Capaldo