【问题标题】:Trying to remove elements in an array : Ruby尝试删除数组中的元素:Ruby
【发布时间】:2021-01-02 16:53:33
【问题描述】:

我正在处理 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

【问题讨论】:

  • 字符串数组* 我添加了 kata 挑战的链接。
  • arr.each_with_index.select {|i,v| v % 2 == 0 }.map(&:first) 可能有用吗?没有测试用例,但用(1..20).to_a 测试。不过,这不是最漂亮的解决方案。
  • 它有效,谢谢伙计。您应该添加答案,如果您可以添加一些关于它如何工作的解释,那就太棒了!
  • @FrederikSpang v.odd?v.even? 是这里的好工具。
  • @FrederikSpang,如果你写arr.select!.with_index { |_,i| i.even? },你就不需要.map(&:first)。请注意,arr 的问题要求将被改变。

标签: arrays ruby list data-structures


【解决方案1】:

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

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

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

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

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

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

【讨论】:

    【解决方案2】:

    可能有多种解决方案。但是 - 不要忘记您不需要删除元素来解决这个挑战 - 您的方法需要返回正确的值,仅此而已。所以下面的代码也应该可以工作:

       arr.select{ |e| arr.find_index(e).even? }
    

    【讨论】:

    • 如果数组包含重复元素,此代码很可能会失败
    • 是的 - 但这个挑战的任务是:'获取一个数组并从数组中删除每隔一个元素。始终保留第一个元素并从下一个元素开始删除。 ;)
    • 是的,这个代码在[1,1,1,1,1]这样的数组上会失败
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 2012-01-12
    • 1970-01-01
    • 2021-05-02
    • 2020-08-14
    相关资源
    最近更新 更多