Beth
Beth

Reputation: 31

How to filter array of strings

I'm trying to isolate certain strings in an array, e.g.,

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

which are identifiable by the start of the string (i.e. substring). I want to keep 'banana man' and 'banana woman' but remove 'apple'. Any help would be appreciated.

Upvotes: 1

Views: 7038

Answers (4)

engineersmnky
engineersmnky

Reputation: 29613

At the Tin Mans behest, and due to the fact that your actual specifications are very vague, I will add this alternative solution as a possible but potentially error prone option.

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

This will out perform grep but is about half the speed of select and start_with? combination and is based solely on the post and not your potentially underlying intentions.

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160631

Benchmark time:

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

Extending 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

Upvotes: 3

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

This is a great usecase for grep

ary = ["banana man", "apple", "banana woman"]
ary.grep(/^banana/) # => ["banana man", "banana woman"]

Upvotes: 9

Paul Rubel
Paul Rubel

Reputation: 27262

Try start_with? and select to choose just those that start with the string you want:

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

Upvotes: 3

Related Questions