Reputation: 686
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"
Upvotes: 2
Views: 194
Reputation: 118299
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"
Upvotes: 3
Reputation: 20398
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('/')
Upvotes: 3
Reputation: 14498
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"
Upvotes: 1