2013-03-30 42 views
2

说我有3个字符串数组:比较字符串并打印出匹配(红宝石)

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

我想比较我的3串并打印出这个新的字符串:

new_string = "/I/love" 

我不想按字符匹配char,只能逐字逐句匹配。有没有人有一个聪明的方式来做到这一点?

由于良好的令牌将我做这个丑陋的代码显示什么功能,我在寻找:

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" 
+0

当你想输出''/ I/love''?你想比较哪些东西?根据你想要产生最终产出的结果? –

+0

嗨。我想比较字符串匹配。如果例如基准[1]是“爱”,所有其他字符串在索引1处都有“爱”,我想将“爱”打印到我的new_string中。现在我想到了,但是我的实例代码太糟糕了,因为如果我添加一个字符串就会破坏我的逻辑。 “I/love/bananas/as/well”,或者多一个“我/爱/香蕉”。 – JohnSmith1976

+0

增加了一个答案。希望它能帮助你。 –

回答

3

这是相同的基本方法如@iAmRubuuu,但在输入处理多于三个的字符串和更简洁和功能性。

strings.map{ |s| s.split('/') }.reduce(:&).join('/') 
+1

不错的一个! 'strings = [“/ I/love/bananas”,“/ I/love/blueberries”,“/ I/love/oranges”] a = strings.each_with_object([]){| i,a | a << i.split('/')} .reduce(:&)。join('/') p a' –

+0

忘记了'inject' /'reduce'的二元运算。 :D –

+0

是的,这也是一个很好的答案。谢谢。 – JohnSmith1976

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" 
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" 
+0

当'map'完成时,不需要'each_with_object'和'<<'。原来只有三个元素的情况下,您的最终裁减才有效。请参阅[我的答案](http://stackoverflow.com/a/15723691/1074296)以获得更清晰的方法。 – dbenhur