【发布时间】:2016-04-06 15:58:01
【问题描述】:
所以我在 Codewars: Flexible Card Game 上尝试一个 kata
http://www.codewars.com/kata/5436fdf34e3d6cb156000350/train/ruby
我编写的代码已经通过了大多数测试,但最后却出现了问题:
#draw
chooses cards from the end
Test Passed: Value == [[:clubs, 13]]
removes cards from the deck
Test Passed: Value == 51
returns the cards that were drawn
Test Passed: Value == 1
Expected [:clubs, 13] to be a Card
chooses cards from the end
Test Passed: Value == [[:clubs, 12], [:clubs, 13]]
removes cards from the deck
Test Passed: Value == 50
returns the cards that were drawn
Test Passed: Value == 2
Expected [:clubs, 12] to be a Card
Expected [:clubs, 13] to be a Card
我不明白的是,当测试调用方法 draw 时,它似乎期望来自同一方法的不同返回。我确定这是我做错了什么,但我看不到。任何帮助都会很棒。这是我的代码:
class Card
include Comparable
attr_accessor :suit, :rank
def initialize(suit, rank)
@suit = suit
@rank = rank
end
def <=> (another_card)
if self.rank < another_card.rank
-1
elsif self.rank > another_card.rank
1
else
0
end
end
def face_card?
@rank > 10 ? true : false
end
def to_s
@rank_hash = {13 => "King", 12 => "Queen", 11 => "Jack", 10 => "10", 9 => "9", 8 => "8", 7 => "7", 6 => "6", 5 => "5", 4 => "4", 3 => "3", 2 => "2", 1 => "Ace"}
@suit_hash = {:clubs => "Clubs", :spades => "Spades", :hearts => "Hearts", :diamonds => "Diamonds"}
"#{@rank_hash[@rank]} of #{@suit_hash[@suit]}"
end
end
class Deck < Card
attr_accessor :cards
def initialize
@rank_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
@suit_array = [:hearts, :diamonds, :spades, :clubs]
@cards = @suit_array.product(@rank_array)
end
def count
@cards.size
end
def shuffle
@cards.shuffle!
end
def draw(n=1)
@cards.pop(n)
end
end
【问题讨论】:
-
What I don't understand is that when the test calls the method draw it seems to expect to different returns from the same method.你能解释一下吗? -
首先它调用 draw 并获取:从最后选择卡片测试通过:Value == [[:clubs, 13]] 但在它再次调用它并想要不同的响应之后,这样说:预期[:clubs, 13] 成为卡片从最后选择卡片我现在明白它需要一个 iff 语句但我不知道如何构造它
-
在
to_s之类的方法中复制@rank_hash和@suit_hash之类的数据是非常低效的,并且为该对象的每个实例声明@suit_array的形式仍然很糟糕。您应该做的是将它们拆分为像RANK_HASH这样的常量,因为它们不会改变并且拥有多个副本是没有意义的。 -
我目前被教导在获得解决方案后进行重构。如果您只是批评形式而不指出错误,那么批评代码似乎毫无意义。我可以在表格工作时修复它。 “你的形式”对我来说没有多大意义,因为我没有你那么先进。感谢您的帮助。
-
如果您自己解决了问题,请将其作为答案或删除问题。不要让已解决的问题悬而未决。
标签: ruby