Как определить, начинаются ли две строки с одной и той же подстроки в ruby? - PullRequest
1 голос
/ 03 ноября 2019

У меня есть две строки, и я хочу определить, начинаются ли две строки с одной и той же подстроки.

str1 = "The cat is black. jkhdkjhdsjhd"

str2 = "The cat is black and white."

str1.starts_with_substring? str2
returns "The cat is black"

str1.starts_with_substring? "The cat"
returns "The cat"

str1.starts_with_substring? "Hello, World!""
returns nil

Я думаю, что мог бы сделать это с помощью итератора, но я надеялся на что-то более сложноев.

Ответы [ 4 ]

4 голосов
/ 03 ноября 2019

Вы можете использовать start_with? и all? для этого:

str1 = "The cat is black. jkhdkjhdsjhd"
str2 = "The cat is black and white."

p [str1, str2].all? { |str| str.start_with?('The cat is') } # true
p [str1, str2].all? { |str| str.start_with?('The cat is not') } # false

И, начиная с Ruby 2.5, Enumerable # any ?, all ?, none? и один? Принимая шаблон в качестве аргумента, вы можете передать регулярное выражение, чтобы проверить, начинается ли каждая строка с этой подстроки:

str1 = "The cat is black. jkhdkjhdsjhd"
str2 = "The cat is black and white."
str3 = "renuncia Piñera The cat is black and white."

p [str1, str2].all?(/\AThe cat is /) # true
p [str1, str2, str3].all?(/\AThe cat is /) # false

После просмотра вопроса в комментариях это может сработать:

str1 = "The cat is black."
str2 = "The cat is black and white."
str3 = "The cat" 

def all_substring?(sentences)
  length = sentences.min.length
  sentences.map { |sentence| sentence[0...length] }.uniq == [sentences.sample[0...length]]
end

p all_substring?([str1, str2, str3]) # true

Если вы не знаете заранее, есть ли подстрока, что искать, я думаю, вы можете использовать самое маленькое предложение в качестве подстроки.

1 голос
/ 03 ноября 2019
def well_do_they?(str1, str2, str)
  len = str.size
  str == str1[0,len] && str == str2[0,len]
end
0 голосов
/ 04 ноября 2019

Какой-нибудь патч обезьяны для String Class?

module MyStringPatch

  def starts_with_substring(other)
    return nil if self[0] != other[0]
    n = (0..self.size).each { |n| break n if self[0..n] != other[0..n] }
    self[0..n-1]
  end

end

String.include MyStringPatch

Так что вы можете позвонить

str1 = "The cat is black. jkhdkjhdsjhd"
str2 = "The cat is black and white."
str1.starts_with_substring str2 #=> "The cat is black"
str1.starts_with_substring "The cat" #=> "The cat"
str1.starts_with_substring "Hello, World!" #=> nil
0 голосов
/ 04 ноября 2019
string = 'The cat is black.'
str1 = 'The cat is black and white.'
str2 = 'The cat'
str3 = 'The dog is white'

def matched_substrings(string, *substrings)
  string = string.gsub('.', '')
  substrings.select do |substring|
    substring = substring.gsub('.', '')
    string.start_with?(substring) || substring.start_with?(string)
  end
end

matched_substrings(string, str1, str2, str3)
#=> ["The cat is black and white.", "The cat"]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...