2

Say I have an array of 3 strings:

strings = ["/I/love/bananas", "/I/love/blueberries", "/I/love/oranges"]

I want to compare my 3 strings and print out this new string:

new_string = "/I/love"

I don't want to match char by char, only word by word. Do anyone have a smart way to do that?

As a token of good will I have made this ugly code to show what functionality I am looking for:

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

You can try the below:

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('/')

or

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

Output:

"2.0.0"
"/I/love"
于 2013-03-30T20:04:45.267 回答
3

This is the same basic approach as @iAmRubuuu, but handles more than three strings in the input and is more concise and functional.

strings.map{ |s| s.split('/') }.reduce(:&).join('/')
于 2013-03-30T21:27:36.297 回答
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 回答