我正在使用Ruby进行Codewar挑战,以从字符串数组中删除元素。到目前为止,我已经尝试使用Array.delete_at(Array.index(value))
,这是要从数组中删除第一次出现的重复值,但是没有用。我相信我可能需要将其与其他内容结合起来,但不确定是什么。
这些是我运行测试时当前的外观:
Expected: ["Hello", "Hello Again"], instead got: ["Hello"]
Expected: [1, 3, 5, 7, 9], instead got: [1]
Test Passed: Value == [[1, 2]]
Test Passed: Value == [["Goodbye"]]
Test Passed: Value == []
到目前为止,我正在使用.shift
方法,这似乎完成了一半的工作。关于如何定位整个子字符串的任何建议。
def remove_every_other(arr)
arr.shift(1)
end
有关更多说明,请找到实践测试并链接到下面的Kata: https://www.codewars.com/kata/5769b3802ae6f8e4890009d2/train/ruby
Test.describe("Basic tests") do
Test.assert_equals(remove_every_other(['Hello', 'Goodbye', 'Hello Again']),['Hello', 'Hello Again'])
Test.assert_equals(remove_every_other([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),[1, 3, 5, 7, 9])
Test.assert_equals(remove_every_other([[1, 2]]), [[1, 2]])
Test.assert_equals(remove_every_other([['Goodbye'], {'Great': 'Job'}]), [['Goodbye']])
Test.assert_equals(remove_every_other([]), [])
end
答案 0 :(得分:3)
Enumerable中有很多工具使这个琐碎事变得如此简单:
a = %w[ a b c d e f ]
a.each_slice(2).map(&:first)
# => ["a", "c", "e"]
首先将数组分割成对,然后取每对中的第一个。
您的shift
方法的问题在于它只执行一项操作,而不会迭代。您必须遍历整个数组才能做到这一点。
现在您可以结合使用shift
和一个累加器,但是当存在更多 functional 版本时,使用给定的数组通常是不好的形式。 each_slice
产生一个新结果,它不会改变原始结果,从而使得在共享输入值的更复杂代码中更容易进行协调。
答案 1 :(得分:1)
可能有多种解决方案。但是-不要忘记,您不需要删除元素来解决这一难题-您的方法需要返回所有正确的值。因此,以下代码也应该起作用:
Neither the property "game" nor one of the methods "getGame()", "game()", "isGame()", "hasGame()", "__get()" exist and have public access in class "App\Entity\Game".