Chris Helgeson
Chris Helgeson

Reputation: 23

Card Class in Ruby

I am fairly new to ruby and am developing a card class. For the most part I got it to work when ever I use a number to define a rank, however when I define the rank as a K (King) it throws back an error message(uninitialized constant). if someone could show me and explain to me what I am doing wrong I would greatly appreciate it

This is my card class

class Card
  attr_accessor :rank, :suit 

  def initialize(the_rank, the_suit)
    @rank = the_rank
    @suit = the_suit
    @symbols = [nil, nil, "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
  end

  def rank
    return @rank
  end

  def suit
    return @suit
  end

  def color
    if @suit == "C" || @suit == "S"
      color = "Black" 
      else
      color = "Red"
    end
  end

  def to_s
    return "#{@symbols[@rank]}#{@suit}"
  end
end

This is a simple test script I have it runs the 7 of clubs fine but can not run the Jack of hearts.

c = Card.new(7, "C") 
print c, "\n"

print c.rank, "\n"

print c.suit, "\n"

print c.color, "\n"


c = Card.new(J, "H") 
print c, "\n"

print c.rank, "\n"

print c.suit, "\n"

print c.color, "\n"

Upvotes: 0

Views: 664

Answers (1)

JTG
JTG

Reputation: 8836

Instead of

c = Card.new(J, "H") 

try

c = Card.new("J", "H") 

This is because J doesn't have any meaning, it's not a defined object; But the string "J", Ruby recognizes that object as a string, thus no error

Upvotes: 2

Related Questions