所以,我通过http://www.rubykoans.com/完成了整个工作,我坚持使用about_scoring_project.rb。这是我对得分方法的刺激。
def score(dice)
score = 0;
if dice.respond_to?("include?") then
# add 1000 points if rolled 3 ones
score += 1000 if dice.include?([1, 1, 1])
# add 100 points times die face value if rolled 3 of a number between 2 and 6
(2...6).each do |die|
score += die*100 if dice.include?([die, die, die])
# award points for each 1 or 5 not a part of a set of 3
leftovers = dice - [1,1,1]
leftovers -= [5,5,5]
leftovers.each do |leftover|
score += 100 if leftover == 1
score += 50 if leftover == 5
end
end
end
score
end
class AboutScoringAssignment < EdgeCase::Koan
def test_score_examples
assert_equal 1150, score([1,1,1,5,1])
assert_equal 0, score([2,3,4,6,2])
assert_equal 350, score([3,4,5,3,3])
assert_equal 250, score([1,5,1,2,4])
end
end
在第一个assert_equal的得分调用中,我希望dice.include?([1,1,1])评估为true,但是它评估为nil(并且得分为0而不是1150)。
我单独尝试了这个......
require 'test/unit'
class EnumerableTests < Test::Unit::TestCase
def test_include
my_enumerable = [1,1,1,5,1]
assert true, my_enumerable.include?([1,1,1])
end
end
......测试通过了,所以我不知道为什么我的得分方法得分为零。
有人看到我做错了吗?
答案 0 :(得分:2)
次要挑剔:Array#include?
始终返回true
或false
,而不是nil
。
要回答您的问题:x.include?(y)
测试y
是x
的元素,而不是它是否为子数组。
[1,1,1,5,1].include?([1,1,1])
返回false
,因为[1,1,1]
不是数组[1,1,1,5,1]
的元素。 [[1,1,1],[5,1]].include?([1,1,1]))
会返回true
。
ruby中没有方法可以检查数组是否是另一个数组的子数组,但是您可以轻松地将其写为arr1.each_cons(arr2.size).include?(arr2)
(在1.8.6中需要require 'enumerator'
)。这是O(arr1.size*arr2.size)
。
如果你想在O(arr1.size + arr2.size)
中使用它,你可以实现Knuth-Morris-Pratt algorithm(这是为了找到子串,但同样适用于查找子数组,因为它们本质上是一样的。)
答案 1 :(得分:0)
我认为你误解了Array#include?
的作用。它将其参数作为数组的元素进行搜索,而不是作为子序列。您的test_include
将始终通过,因为您将assert
函数true
作为其第一个参数。你应该使用assert_equal
和这些参数,或者(最好)去除第一个参数。