Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if the end of a string overlaps with beginning of a separate string

Tags:

ruby

I want to find if the ending of a string overlaps with the beginning of separate string. For example if I have these two strings:

string_1 = 'People say nothing is impossible, but I'
string_2 = 'but I do nothing every day.'

How do I find that the "but I" part at the end of string_1 is the same as the beginning of string_2?

I could write a method to loop over the two strings, but I'm hoping for an answer that has a Ruby string method that I missed or a Ruby idiom.

like image 691
Chris C Avatar asked Aug 22 '18 17:08

Chris C


1 Answers

Set MARKER to some string that never appears in your string_1 and string_2. There are ways to do that dynamically, but I assume you can come up with some fixed such string in your case. I assume:

MARKER = "@@@"

to be safe for you case. Change it depending on your use case. Then,

string_1 = 'People say nothing is impossible, but I'
string_2 = 'but I do nothing every day.'
(string_1 + MARKER + string_2).match?(/(.+)#{MARKER}\1/) # => true

string_1 = 'People say nothing is impossible, but I'
string_2 = 'but you do nothing every day.'
(string_1 + MARKER + string_2).match?(/(.+)#{MARKER}\1/) # => false
like image 69
sawa Avatar answered Sep 30 '22 05:09

sawa