each_charを使用しているときに、繰り返し数を追跡するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/815977

質問

Rubyを学んでいて、Binary-> Decimalコンバーターを作成することを考えています。バイナリ文字列を取得し、同等の10進数に変換します。変数「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

Googleからこの回答を見つけた人(私のような)のために、

バイナリを変換する簡単な方法->ルビーの小数(および再び):

# 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