2

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"
4

3 に答える 3

3

以下を試すことができます:

p RUBY_VERSION
strings = ["/I/love/bananas", "/I/love/blueberries", "/I/love/oranges"]
a = strings.each_with_object([]) { |i,a| a << i.split('/') }
p (a[0] & a[1] & a[2]).join('/')

また

strings = ["/I/love/bananas", "/I/love/blueberries", "/I/love/oranges"]
a = strings.each_with_object([]) { |i,a| a << i.split('/') }.reduce(:&).join('/')
p a

出力:

"2.0.0"
"/I/love"
于 2013-03-30T20:04:45.267 に答える
1
str = ["/I/love/bananas", "/I/love/blueberries", "/I/love/oranges"]

tempArr = []

str.each do |x|
    tempArr << x.split("/")
end
(tempArr[0] & tempArr[1] & tempArr[2]).join('/') #=> "/I/love"
于 2013-03-30T19:37:00.910 に答える