1

Given two string like the ones below, I would like to merge them to generate the following. The results makes little sense, however, both strings have 'a sentence' in common, which is what counts as the connector between the two strings:

"This is a sentence is a great thing"

s1 = "This is a sentence" 

s2 = "a sentence is a great thing"

Is there a function for this in ruby?

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
Jackson Henley
  • 1,531
  • 2
  • 15
  • 27

4 Answers4

2

Here's a solution that works.

def str_with_overlap(s1, s2)
  result = nil
  (0...(s2.length)).each do |idx|
    break result = s1 + s2[(idx + 1)..-1] if s1.end_with?(s2[0..idx])
  end
  result
end

str_with_overlap("This is a sentence", "a sentence is a great thing")
# => This is a sentence is a great thing
d11wtq
  • 34,788
  • 19
  • 120
  • 195
1

As far as I know, there is no built-in function for this in Ruby.

You probably have to write an own function for this. The straightforward one runs in quadratic time in the input length. However, it is possible to do it in linear time in the input size by using this algorithm.

Community
  • 1
  • 1
Allan D.
  • 163
  • 1
  • 8
1

there is no built-in method in Ruby, but u can try this one

class String
  def merge str
    result = self + str
    for i in 1..[length,str.length].min
      result = self[0,length-i] + str if self[-i,i] == str[0,i]
    end
    result
  end
end

"This is a sentence".merge "a sentence is a great thing"
Yuri Barbashov
  • 5,407
  • 1
  • 24
  • 20
0

Functional approach (works at word-level):

ws1, ws2 = [s1, s2].map(&:split)
idx = 0.upto(ws1.size-1).detect { |i| ws1[i..-1] == ws2[0, ws1.size-i] } || 0
(ws1[0, ws1.size-idx] + ws2).join(" ")
=> "This is a sentence is a great thing"
tokland
  • 66,169
  • 13
  • 144
  • 170