-1

I am trying to write a Ruby program to deal 2 cards to one player but I get the error message no implicit conversion of Fixnum into string. I have looked at similar questions and I do not think they apply to this issue. I would appreciate any help with this. Here is my code:

def get_card (card)
  suit = (card - 1)/13
  if (card == 0)
    puts " of clubs"
  elsif (card == 1)
    puts " of diamonds"
  elsif (card == 2)
    puts " of hearts"
  elsif (card == 3)
    puts " of spades"
  end

  card % 13
  if (card == 1)
    return "ace" + suit
  elsif (card == 11)
    return "jack" + suit
  elsif (card == 0)
    return "king" + suit
  elsif (card == 2)
    return "2" + suit
  elsif (card == 3)
    return "3" + suit
  elsif (card == 4)
    return "4" + suit
  elsif (card == 5)
    return "5" + suit
  elsif (card == 6)
    return "6" + suit
  elsif (card == 7)
    return "7" + suit
  elsif (card == 8)
    return "8" + suit
  elsif (card == 9)
    return "9" + suit
  elsif (card == 10)
    return "10" + suit
  elsif (card == 12)
    return "queen" + suit
  end
end

def deal_cards
  total_cards = (1..52).to_a.shuffle
  player_value = [total_cards.pop, total_cards.pop]
  puts "Your cards are " + get_card(player_value[0]).to_s + " and " + get_card(player_value[1]).to_s
end

deal_cards
Anthony
  • 15,435
  • 4
  • 39
  • 69
DBL
  • 45
  • 1
  • 1
  • 5
  • Can you reduce this example to a something very small? It should be possible to create a one-liner, or a piece of code with only one or two significant lines, which shows this problem. – Graham Asher Dec 12 '15 at 21:57

2 Answers2

2

This is easy to see on the command line, where you pick your cards at random and the suit.

When you go to output the results of the deal to the screen, you do so using:

return "5" + suit

The goal here being that you want "5spades" or better, "5 of spades". The problem here is that suit is a Fixnum object, or very similar to an int.

While the class String does have a + operator it can only be used with other strings.

Here's an example to reproduce your error:

"ace" + 1
TypeError: no implicit conversion of Fixnum into String

To get what your after in simple terms, you can either convert the Fixnum to a string via .to_s like this:

> "ace" + 1.to_s
=> "ace1"

Or you can use string interpolation like this:

> "ace#{1}"
=> "ace1"
Anthony
  • 15,435
  • 4
  • 39
  • 69
  • Thanks so much for your help. I now have another problem displaying the values. It says your cards are and . Is there something else that needs to be fixed? – DBL Dec 12 '15 at 22:46
  • Change the line `card % 13` to `card = card % 13` – spickermann Dec 12 '15 at 22:56
1

I think your problem could be here:

return "ace" + suit

where ace is a String and suit is an Integer suit = (card - 1)/13

You do the same thing with for king, queen, jack

NickGnd
  • 5,107
  • 1
  • 20
  • 26