我使用Ruby的子方法来清理一些字符串这样的数组:使用Ruby的子方法用绳子
test_string = 'we serve food and drinks'
=> "we serve foo and drinks"
test_string.sub('and drinks', '')
=> "we serve foo"
我怎样可以用同样的方法在一个字符串数组像这样的:
test_array = ['we serve foo and drinks', 'we serve toasts and drinks', 'we serve alcohol and drinks']
我试过以下摆脱“和饮料”这个数组中的每个字符串的一部分,但我无法删除它们。
test_array.each do |testArray|
test_array.sub('and drinks', '')
end
=> ["we serve foo and drinks", "we serve toasts and drinks", "we serve kale and drinks"]
请定义“不起作用”。你期望的结果是什么?你为什么期待这样的结果?你得到了什么结果?为什么你的结果不是你期望的结果?你是如何得到这个结果的?请提供[mcve]以及所有错误信息和警告信息,预期结果和实际结果,预期和实际行为,以及包括示例在内的明确问题陈述以及所有角落案例,特殊案例,边缘案例的规范,以及如何获得预期结果的所有规则。目前,你只是忽略了'sub'的结果,那么你怎么知道这个...... –
“它不工作”? –
我认为当你比较我提供的两个例子时,什么都不起作用。当应用于一个字符串时,我能够使用子方法获得非常清晰的结果,但是当将相同的方案应用于字符串数组时,它不会产生相同的结果,这基本上与我的第一个示例重复。最初的答案在7分钟内降落了一个工作解决方案,所以我认为这足够清楚。 – cinnaroll45