Robertgold
Robertgold

Reputation: 225

`-': no implicit conversion of Fixnum into Array

A user inputs coins in a comma-separated list, and then they put a colon before the amount of change they want. We have coins: £1 (100p), 50p, 20p, 10p, 5p, 2p, and 1p, and we wish to give the customer 57p. The data input would be like this: 100,50,20,10,5,2,1:57. Change is given to the user in the simplest way.

This is my code:

user_input = gets
i = 0
change_needed = 67  
coins = [50,5,20,1,5]
check_input = user_input.length
coins = user_input.split(',')
change_needed = user_input.split(':')
coins_length = coins.length
coins.map!(&:to_i)
coins = coins.sort {|a,b| b <=> a}
if check_input < 100 then
  while change_needed != 0 do
    if change_needed - coins[i] then
      change_needed -= coins[i]
    else
      i += 1
      puts "#{i} is the number in the coin array"
    end
  end
else
end

I get the following error message on the line if change_needed - coins[i] then:

rb:17:in `-': no implicit conversion of Fixnum into Array (TypeError)

I don't understand this error message. It seems to be a simple fix, but I can't grasp what I need to do with my code to fix it.

Upvotes: 0

Views: 2899

Answers (1)

Mario Zannone
Mario Zannone

Reputation: 2883

In change_needed = user_input.split(':') you are setting change_needed to an array, not to an int.

Try replacing:

coins = user_input.split(',')
change_needed = user_input.split(':')

with

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

Upvotes: 1

Related Questions