好像我的代码永远不会通过switch语句运行。每次我创建一个Deck对象时,每个Card对象的套装和名称都是nil。任何人都可以帮助我吗?
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
答案 0 :(得分:8)
case
语句隐式应用===
运算符。所以你想要更像的东西:
case j
when 2 then "Two of #{suit}"
when 3 then "Three of #{suit}"
# ...
end
答案 1 :(得分:6)
你的case语句不应该包含实际的布尔比较,而应该是文字,比如:
case j
when 2
"Two of #{suit}"
when 3
"Three of #{suit}"
end
答案 2 :(得分:1)
没有理由开始使用case
。你甚至不需要哈希,一对阵列就可以了:
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
答案 3 :(得分:0)
Jeremy和Cody已经回答正确了。只是另一种观点:
你对i == 0的when子句测试。这个比较返回true或false。 因此,当您测试为true时,您的代码可以正常工作:
[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
}
请不要使用这样的代码。它可能有用,但这是无稽之谈。使用Jeremy和Cody已发布的代码:
[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
}