2009-05-03 34 views
1

我在学Ruby,想到制作Binary-> Decimal转换器。它得到一个二进制字符串并转换为十进制等值。有没有办法跟踪ruby中的当前迭代步骤,以便可以删除变量“x”?如何在使用each_char时跟踪迭代次数?

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 

回答

5

是,通过使用非常强大的枚举库:

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 

顺便说一句,你可能感兴趣的Array#packString#unpack。他们支持位串。另外,获得该结果的更简单的方法是使用#to_i,例如, "101".to_i(2) #=> 5

1
binary_string.reverse.chars.each_with_index do |binary, i| 
    decimal_equivalent += binary.to_i * (2 ** i) 
end 

或者上比1.8.7老版本:

binary_string.reverse.split(//).each_with_index do |binary, i| 
    decimal_equivalent += binary.to_i * (2 ** i) 
end 
+0

它说未定义方法 字符为“0”:字符串 – unj2 2009-05-03 01:13:38

0

对于谁发现从谷歌这个答案的人(比如我),

下面是二进制转换的简单方法 - >十进制的红宝石(和回来):

# The String.to_i function can take an argument indicating 
# the base of the number represented by the string. 
decimal = '1011'.to_i(2) 
# => 11 

# Likewise, when converting a decimal number, 
# you can provide the base to the to_s function. 
binary = 25.to_s(2) 
# => "11001" 

# And you can pad the result using right-justify: 
binary = 25.to_s(2).rjust(8, '0') 
# => "00011001"