2009-05-03 24 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" 
相關問題