3 つの文字列の配列があるとします。
strings = ["/I/love/bananas", "/I/love/blueberries", "/I/love/oranges"]
3 つの文字列を比較して、この新しい文字列を出力したい:
new_string = "/I/love"
文字ごとに一致させるのではなく、単語ごとにのみ一致させます。誰かがそれを行う賢い方法を持っていますか?
善意のしるしとして、私が探している機能を示すために、この醜いコードを作成しました。
strings = ["/I/love/bananas", "/I/love/blueberries", "/I/love/oranges"]
benchmark = strings.first.split("/")
new_string = []
strings.each_with_index do |string, i|
unless i == 0
split_string = string.split("/")
split_string.each_with_index do |elm, i|
final_string.push(elm) if elm == benchmark[i] && elm != final_string[i]
end
end
end
final_string = final_string.join("/")
puts final_string # => "/I/love"