Jackson Henley
Jackson Henley

Reputation: 1531

Ruby function to merge two string into one

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?

Upvotes: 1

Views: 923

Answers (4)

Yuri  Barbashov
Yuri Barbashov

Reputation: 5437

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"

Upvotes: 1

tokland
tokland

Reputation: 67860

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"

Upvotes: 0

d11wtq
d11wtq

Reputation: 35308

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

Upvotes: 2

Allan D.
Allan D.

Reputation: 163

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.

Upvotes: 1

Related Questions