【发布时间】: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