Longest Common Prefix in Ruby

Ruby @ Freshers.in

Finding the longest common prefix among a set of strings is a common task in string manipulation and text processing. In Ruby, mastering the technique to achieve this efficiently is crucial for various applications. In this article, we’ll explore how to implement a function in Ruby to find the longest common prefix among an array of strings, accompanied by detailed examples and outputs to enhance your string manipulation skills.

Understanding Longest Common Prefix

The longest common prefix is the longest string that is a prefix of all strings in a given set of strings.

Example: Finding Longest Common Prefix in Ruby

Let’s define a Ruby function called longest_common_prefix to find the longest common prefix among an array of strings.

def longest_common_prefix(strs)
  return '' if strs.empty?

  prefix = strs.first
  strs[1..-1].each do |str|
    prefix = prefix[0...str.size].chars.zip(str.chars).take_while { |a, b| a == b }.map(&:first).join
  end

  prefix
end

# Test the function with examples
strings1 = ["flower", "flow", "flight"]
strings2 = ["dog", "racecar", "car"]

puts "Longest Common Prefix for strings1: #{longest_common_prefix(strings1)}"  # Output: fl
puts "Longest Common Prefix for strings2: #{longest_common_prefix(strings2)}"  # Output: ''

Output:

Longest Common Prefix for strings1: fl
Longest Common Prefix for strings2: 

In this example, the longest_common_prefix function correctly identifies the longest common prefix among the given arrays of strings.

Get more useful articles on Ruby

Author: user