كيف يمكنني تتبع عدد التكرار أثناء استخدام each_char؟
سؤال
وأنا أتعلم روبي والفكر من صنع Binary-> تحويل عشري. فإنه يحصل على السلسلة الثنائية والمتحولين إلى ما يعادل عشري. هل هناك طريقة لتتبع الخطوة التكرار الحالية في روبي بحيث المتغير '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"
لا تنتمي إلى StackOverflow