`[]':没有将String隐式转换为Integer(TypeError)

时间:2017-05-03 19:51:56

标签: ruby array-algorithms

我似乎在以下代码中遇到类型错误:

    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)

任何人都可以帮助我吗?

我认为我正在使用数组作为整数,但我无法看到可能的位置。

2 个答案:

答案 0 :(得分:3)

正如Brian所说,你错误地解释了each如何使用块参数

而不是

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

您只需引用元素

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

如果您确实想要数组的索引,可以使用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

或只使用一系列索引值

(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”之类的字符串,则i包含“7”并且您正尝试访问hand_array [“7”] ... in换句话说,尝试使用字符串而不是整数来访问数组元素。并且Ruby不会自动(隐式)将字符串转换为数组索引的整数。

答案 1 :(得分:1)

这条线似乎很可疑:

if colored_mana_hand.include?(colored_mana_cost_aggregate[i])

在此上下文中,icolored_mana_cost_aggregate的元素(来自之前行的each迭代器),并且您尝试将其用作数组索引。