Reputation: 31
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
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
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
Reputation: 230561
This is a great usecase for grep
ary = ["banana man", "apple", "banana woman"]
ary.grep(/^banana/) # => ["banana man", "banana woman"]
Upvotes: 9
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