2017-05-03 9 views
0

私は、次のコードでは型エラーを取得しているようだ:`[] ':整数に文字列のいない暗黙の変換(TypeError例外)

def can_cast(hand, *spell_cost) 
     colored_mana_hand = Array.new 
     colored_mana_cost_aggregate = Array.new 
     colored_mana_spent = Array.new 
     colorless_mana_hand = 0 
     colorless_mana_cost_aggregate = 0 

     hand_array = hand.split("").sort 
     total_cost = spell_cost.join.split("").sort 

     hand_array.each do |i| 
     if hand_array[i].to_i != 0      
     colorless_mana_hand += hand_array[i].to_i 
     else 
     colored_mana_hand << hand_array[i] 
     end 
    end 

    total_cost.each do |i|     
     if total_cost[i].to_i != 0     
     colorless_mana_cost_aggregate += total_cost[i].to_i 
     else 
     colored_mana_cost_aggregate << total_cost[i] 
     end 
    end 

colored_mana_cost_aggregate.each do |i|             
    if colored_mana_hand.include?(colored_mana_cost_aggregate[i]) 
    colored_mana_spent << colored_mana_cost_aggregate[i]   
colored_mana_hand.rotate(colored_mana_hand.index(colored_mana_cost_aggregate[i])).shift 
    end 
end 

    colored_mana_spent == colored_mana_cost_aggregate && (colored_mana_hand.length + colorless_mana_hand) >= colorless_mana_cost_aggregate 
    end 

それはこの

`[]': no implicit conversion of String into Integer (TypeError) 

のようでしたに見えます誰でも助けてくれますか?

私は整数として配列を使用していると思いますが、その可能性があるのはわかりません。

+0

Rubyのプログラマーではありませんが、文字列をIntegerとして使用しようとしていると不満を持ち、あなたが知らないうちにそうしたくないという不満があります。 to_iを見てください:https://apidock.com/ruby/String/to_i – Qrchack

+2

例外に関する情報を提供する際には、それを発生させたコード行を含めてください。 –

答えて

1

この行は、疑わしいと思われる。このような状況において

if colored_mana_hand.include?(colored_mana_cost_aggregate[i]) 

iは(前の行にeachイテレータから)colored_mana_cost_aggregateの要素であり、あなたは配列のインデックスとして使用しようとしています。ブライアンが言うように

+0

ああ、それは明確な感謝の男です。 –

3

、あなたが実際にしたい場合はあなただけの要素

hand_array.each do |hand| 
    if hand.to_i != 0      
    colorless_mana_hand += hand.to_i 
    else 
    colored_mana_hand << hand 
    end 
end 

を参照する方法を代わりに

hand_array.each do |i| 
    if hand_array[i].to_i != 0      
    colorless_mana_hand += hand_array[i].to_i 
    else 
    colored_mana_hand << hand_array[i] 
    end 
end 

のブロックパラメータ

each作品誤解しています配列のインデックス、使用することができますeach_with_index

hand_array.each_with_index do |_hand, i| 
    if hand_array[i].to_i != 0      
    colorless_mana_hand += hand_array[i].to_i 
    else 
    colored_mana_hand << hand_array[i] 
    end 
end 

か、単にエラーを意味まさに... hand_arrayは、このような「7」は、その後iは「7」が含まれ、あなたがしているように文字列が含まれている場合については

(0...hand_array.count).each do |i| 
    if hand_array[i].to_i != 0      
    colorless_mana_hand += hand_array[i].to_i 
    else 
    colored_mana_hand << hand_array[i] 
    end 
end 

値インデックスの範囲を使用しますhand_array ["7"]にアクセスしようとしています...つまり、整数の代わりに文字列を使用して配列要素にアクセスしようとしています。そしてRubyは文字列を自動的に(暗黙的に)配列インデックスの整数に変換しません。

関連する問題