0

It seems as if my code never runs through the switch statement. Every time I create a Deck object, every Card object has nil for both the suit and the name. Can anyone help me out?

class Card def initialize (suit, number, name) @suit = suit @number = number @name = name # end attr_reader :suit, :number, :name end class Deck def initialize @deck = Array.new for i in 0...4 suit = case i when i == 0 then "Spades" when i == 1 then "Hearts" when i == 2 then "Diamonds" when i == 3 then "Clubs" end puts i puts suit #Debug only for j in 2...15 name = case j when j == 2 then "Two of #{suit}" when j == 3 then "Three of #{suit}" when j == 4 then "Four of #{suit}" when j == 5 then "Five of #{suit}" when j == 6 then "Six of #{suit}" when j == 7 then "Seven of #{suit}" when j == 8 then "Eight of #{suit}" when j == 9 then "Nine of #{suit}" when j == 10 then "Ten of #{suit}" when j == 11 then "Jack of #{suit}" when j == 12 then "Queen of #{suit}" when j == 13 then "King of #{suit}" when j == 14 then "Ace of #{suit}" end puts j puts name #Debug only @deck.push(Card.new(suit, j, name)) end end end attr_reader :deck end 
1
  • 1
    Less repetition: suit = %w[Spades Hearts Diamonds Clubs][i]; name = %w[Two Three Four Five Six Seven Eight Nine Ten Jack Queen King Ace][j-2] + " of #{suit}" Commented Aug 1, 2011 at 23:11

4 Answers 4

8

The case statement implicitly applies the === operator. So you want something more like:

case j when 2 then "Two of #{suit}" when 3 then "Three of #{suit}" # ... end 
Sign up to request clarification or add additional context in comments.

Comments

6

Your case statement shouldnt contain the actual boolean comparisons, but instead should be the literals, like:

case j when 2 "Two of #{suit}" when 3 "Three of #{suit}" end 

1 Comment

Thanks, your answer was awesome too.
1

No reason to use case for this to begin with. You don't even need Hashes, a couple Arrays would do fine:

suits = %w{Spades Hearts Diamonds Clubs} values = %w{- - Two Three Four Five Six Seven Eight Nine Ten Jack Queen King Ace} deck = suits.map do |s| (2..14).map do |i| Card.new(s,i,"#{values[i]} of #{s}") end end.flatten 

Comments

0

Jeremy and Cody already answered correct. Just another view:

Your when-clause test for i == 0. This comparison returns true or false. So, when you test for true, your code could work:

[0,1,2,3 ].each{|i| print "Test #{i}. Hit: " case true when i == 0 then puts "Spades" when i == 1 then puts "Hearts" when i == 2 then puts "Diamonds" when i == 3 then puts "Clubs" end } 

Please don't use code like this. It may work, but it's nonsense. Use the code Jeremy and Cody already posted:

[0,1,2,3 ].each{|i| print "Test #{i}. Hit: " case i when 0 then puts "Spades" when 1 then puts "Hearts" when 2 then puts "Diamonds" when 3 then puts "Clubs" end } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.