How can I find the the substring that is closest to another substring in Ruby?
Let's say I have the following string:
here is some text in a sentence 55 and some other text still in the same sentence
There are two instances of the substring sentence
in the string. How can I find the instance that is closest to the substring 55
?
I am using Ruby 1.9.2
Split the string on the marker:
first, last = str.split("55")
Distance from the second is simply via #index:
last_dist = last.index("sentence")
Distance from the first is slightly funkier:
first_dist = first.reverse.index("sentence".reverse")
Compare:
result = first_dist < last_dist ? :first : :last
str = "here is some text in a sentence 55 and some other text still in the same sentence"
t = str.index('55')
p [str.index('sentence', t), str.rindex('sentence', t)].min_by{|pos| (pos-t).abs}
More common solution for more than two substrings:
str = "text sub text text sub key text sub"
positions = []
last_pos = nil
key_pos = str.index('key')
while (last_pos = str.index('sub', (last_pos ? last_pos + 1 : 0)))
positions << last_pos
end
p positions.map{|p| (p-key_pos).abs}.min
精彩评论