首页 > 解决方案 > 尝试删除数组中的元素: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

标签: arraysrubylistdata-structures

解决方案


Enumerable中有很多工具可以让这变得微不足道:

a = %w[ a b c d e f ]

a.each_slice(2).map(&:first)
# => ["a", "c", "e"]

首先将数组分成对,然后取每对中的第一个。

您的shift方法的问题是它只执行一项操作,而不是迭代。您必须通过整个阵列来实现这一点。

现在您可以使用shift和 累加器的组合,但是当存在功能更强大的版本时,使用您提供的数组通常是不好的形式。each_slice产生一个新结果,它不会改变原始结果,从而更容易在可能共享输入值的更复杂的代码中进行协调。


推荐阅读