我正在研究Ruby中的Codewar挑战,以从字符串数组中删除元素。到目前为止,我已经尝试过使用Array.delete_at(Array.index(value))
which来从数组中删除重复出现的值的第一次出现,但是这没有用。我认为我可能需要将其与其他内容结合起来,但不确定是什么。
这些是我运行测试时当前的外观:
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
Enumerable中有很多工具使这个琐碎的事情变得很简单:
a = %w[ a b c d e f ]
a.each_slice(2).map(&:first)
# => ["a", "c", "e"]
首先将阵列分成几对,然后取每对中的第一对。
您的shift
方法的问题在于它只执行一项操作,不会迭代。您必须遍历整个数组才能做到这一点。
现在,您可以结合使用shift
和累加器,但是当存在更多功能版本时,使用给定的数组通常是不好的形式。each_slice
产生一个新的结果,它不会改变原始结果,从而使得在共享输入值的更复杂的代码中更容易进行协调。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句