arrays - 尝试删除数组中的元素:Ruby
问题描述
我正在处理 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
产生一个新结果,它不会改变原始结果,从而更容易在可能共享输入值的更复杂的代码中进行协调。
推荐阅读
- bash - Bash shell 在新文件上继续嵌套循环
- python - Windows 中的 TensorFlow 安装错误:没有名为“_pywrap_tensorflow_internal”的模块
- python - 自动迭代列表的索引
- typescript - 如何用 typescript 的接口描述 mobx-state-tree 的模型?
- geospatial - 如何在qgis中提取多边形的空间属性?
- javascript - 如何从数据库php中的动态下拉列表和文本框中保存多个值
- linux - 如何释放linux服务器上的cashed memory
- python - 在 unicode 和 text 上使用 re 拆分 python 字符串
- c++ - c++ 11 如何获取系统时间?
- django - 编写使用主数据库的 django 测试