Search code examples
arraysrubystringfixnum

String can't be coerced into Fixnum


I have this error on this line (if change_needed - coins[i] >= 0 then )

String can't be coerced into Fixnum

From my code, I don't understand why it won't work right now. Any help on how best to solve this issue would be greatly appreciated.

user_input = gets
change_needed = 0
coins = []

coins_part, change_needed_part = user_input.split(':')
coins = coins_part.split(',')
change_needed = change_needed_part.to_i

i = 0
coins_used = []

while change_needed != 0 do
  if change_needed - coins[i] >= 0 then
    change_needed = change_needed - coins[i]
    coins_used << coins[i]
  else
    i += 1
  end
end

Solution

  • coins is an array of String, while you are trying to do arithmetic operation with coins[i].

    Change

    coins = coins_part.split(',')
    

    to

    coins = coins_part.split(',').map(&:to_i)