我正在学习Ruby,并考虑制作二进制 - >十进制转换器。它获取二进制字符串并转换为十进制等效值。有没有办法跟踪ruby中的当前迭代步骤,以便可以删除变量'x'?

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
有帮助吗?

解决方案

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

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#pack String#unpack 感兴趣。他们支持位串。此外,获得此结果的更简单方法是使用 #to_i ,例如" 101" .to_i(2)#=> 5

其他提示

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

对于那些从谷歌找到这个答案的人(比如我),

这是转换二进制文件的简便方法 - >红宝石中的小数(又返回):

# 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"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top