eary_char를 사용하는 동안 반복 번호를 추적하려면 어떻게해야합니까?
문제
나는 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
구글 에서이 답을 찾은 사람들 (나 같은)을 위해
Ruby에서 바이너리 -> 10 진수를 변환하는 쉬운 방법은 다음과 같습니다.
# 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"
제휴하지 않습니다 StackOverflow