如何过滤字符串数组

时间:2015-10-13 15:30:52

标签: arrays ruby string substring

我试图隔离数组中的某些字符串,例如,

["banana man", "apple", "banana woman"]

可由字符串的开头(即子字符串)识别。我想保留'banana man''banana woman',但请删除'apple'。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:5)

这是grep

的一个很好的用例
ary = ["banana man", "apple", "banana woman"]
ary.grep(/^banana/) # => ["banana man", "banana woman"]

答案 1 :(得分:3)

尝试使用start_with?select来选择那些以您想要的字符串开头的内容:

["banana man", "apple", "banana woman"].select { |i| i.start_with?("bana") }
=> ["banana man", "banana woman"]

答案 2 :(得分:2)

基准时间:

require 'fruity'

ARY = ["banana man", "apple", "banana woman"]

ARY.grep(/^banana/) # => ["banana man", "banana woman"]
ARY.select { |i| i.start_with?("bana") } # => ["banana man", "banana woman"]

compare do
  grep_only { ARY.grep(/^banana/) }
  select_start_with { ARY.select { |i| i.start_with?("bana") } }
end
# >> Running each test 4096 times. Test will take about 1 second.
# >> select_start_with is faster than grep_only by 3x ± 1.0

扩展ARY

ARY = ["banana man", "apple", "banana woman"] * 1000

compare do
  grep_only { ARY.grep(/^banana/) }
  select_start_with { ARY.select { |i| i.start_with?("bana") } }
end
# >> Running each test 8 times. Test will take about 1 second.
# >> select_start_with is faster than grep_only by 3x ± 0.1

答案 3 :(得分:0)

在Tin Mans的要求下,由于您的实际规格非常模糊,我会将此替代解决方案添加为可能但容易出错的选项。

ARY = ["banana man", "apple", "banana woman"] 
ARY.join('  ').scan(/banana\s\w+/)
#=> ["banana man", "banana woman"]

这将执行grep,但速度只有selectstart_with?组合的一半,并且仅基于帖子,而不是您潜在的潜在意图。