在数组中匹配子字符串

时间:2016-07-03 12:46:17

标签: arrays ruby string

我正在寻找一种方法,可以检查数组中字符串的第一个 n 字符是否相同。

例如:

["Marseille", "Marsan", "Martin"].method(3) => true
["Mar", "Mar", "Mar"]
["Marseille", "Marsan", "Martin"].method(4) => false
["Mars", "Mars", "Mart"]

4 个答案:

答案 0 :(得分:4)

较短的版本会使用Array#uniq一个块和Enumerable#one?

class Array
  def same_prefix?(n)
    uniq{|x| x[0, n]}.one?
  end
end

Demonstration

答案 1 :(得分:2)

使用Array#map获取前缀数组:

["Marseille", "Marsan", "Martin"].map { |x| x[0,4] }.uniq
# => ["Mars", "Mart"]

Array#uniq删除重复的项目。

class Array
  def same_prefix?(n)
    self.map { |x| x[0, n] }.uniq.size == 1
  end
end

["Marseille", "Marsan", "Martin"].same_prefix?(3)
# => true
["Marseille", "Marsan", "Martin"].same_prefix?(4)
# => false

如果所有前缀都相同,则结果应该是单个项目的数组。

"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-*",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final"

答案 2 :(得分:1)

class Array
  def same_start?(n)
    start = first[0,n]
    all? { |e| e[0,n] == start }
  end
end

["Marseille", "Marsan", "Martian"].same_prefix?(3) #=> true
["Marseille", "Marsan", "Martian"].same_prefix?(4) #=> false

答案 3 :(得分:0)

以下是另一种方法:

arr = ["Marseille", "Marsan", "Martin"]
n = 3
arr.each_cons(2).all? {|s1, s2| s1[0...n] == s2[0...n]}
#=> true

轻微变体可以是:

arr.map{|s| s[0...n]}.each_cons(2).all? {|s1, s2| s1 == s2}