我用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"]

最佳答案

使用#map

test_array.map do |testArray|
  testArray.sub('and drinks', '')
end

也可以对每个字符串进行变异(不推荐这样做)
test_array.each do |testArray|
  testArray.sub!('and drinks', '')
end

关于ruby-on-rails - 将Ruby子方法与字符串数组一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41243767/

10-12 07:34