Thomas Billot
Thomas Billot

Reputation: 163

Matching Substrings in arrays

I'm looking for a little method that could check if the first n characters of string in the array are the same.

For example:

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

Upvotes: 2

Views: 60

Answers (4)

Wand Maker
Wand Maker

Reputation: 18772

Here is one more way to do this:

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

A slight variant can be:

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

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110755

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

Upvotes: 1

potashin
potashin

Reputation: 44611

A shorter version would be using Array#uniq with a block and Enumerable#one?:

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

Demonstration

Upvotes: 4

falsetru
falsetru

Reputation: 369454

Use Array#map to get prefix array:

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

and Array#uniq to remove duplicated items.

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

If all prefixes are same, result should be an array of single item.


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

Upvotes: 2

Related Questions