Pregunta

Estoy aprendiendo a Ruby y pensé en hacer un convertidor de decimal y binario. Obtiene una cadena binaria y se convierte en equivalente decimal. ¿Hay alguna forma de seguir el paso de la iteración actual en ruby ??para poder eliminar la variable '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
¿Fue útil?

Solución

Sí, utilizando la muy poderosa biblioteca de enumeradores:

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

Por cierto, puede estar interesado en Array # pack y String # unpack . Tienen soporte para cadenas de bits. Además, una forma aún más fácil de obtener este resultado es utilizar #to_i , por ejemplo. " 101 " .to_i (2) # = > 5

Otros consejos

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

O en versiones anteriores a 1.8.7:

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

Para las personas (como yo) que encontraron esta respuesta de google,

Aquí está la manera fácil de convertir binario - > decimal en rubí (y de nuevo):

# 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"
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top