ruby - 如何确定两个字符串是否以 ruby​​ 中的相同子字符串开头

标签 ruby string

我有两个字符串,想判断这两个字符串是否以相同的子字符串开头。

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

我想我可以用一个迭代器来做到这一点,但我希望有更多内置的东西。

最佳答案

您可以为此使用 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

如果你不能事先知道是否有一个要查找的子串,我认为你可以使用最小的句子作为子串。

关于ruby - 如何确定两个字符串是否以 ruby​​ 中的相同子字符串开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58683506/

相关文章:

ruby - Rails 控制台未将 SQL 语句输出到我的开发日志

ruby - 我如何检测 Ruby 中的文件结尾?

ruby-on-rails - 当我在 ruby​​ 中使用系统命令创建 TAR 时出现错误 "tar: Invalid transform expression"。为什么?

ruby-on-rails - 如何在 Ruby on Rails 中循环几个月

c++ - 我正在尝试从类中的 boolean 值返回一个字符串,该字符串一直返回 true

javascript - 如何根据一个或多个重复字符的模式拆分字符串并保留匹配项?

c# - 带有模式变量的 Regex.Replace()

c - 如何在 C 编程中将两个字符串数组放在一起

c - C中的字符串输入和输出

ruby-on-rails - Geocoder:.nearbys 方法抛出 ActionView::Template::Error (nil:NilClass 的未定义方法 `each'):