2014-08-27 71 views
0

我是(非常)新的紅寶石,無法弄清楚爲什麼我的rspec掛起。我在下面給出的方法中有兩個正則表達式。如果我也註釋掉,rspec的作品。但是,如果兩者都存在,rspec的掛起(link to full project, including tests,如果它可以幫助提供上下文)Rspec測試與正則表達式掛起

樣品輸入:

pairings= [["Joe Johnson", "Jane Johnson"], ["Sarah Smith", "Bob Jones"]] 

期望輸出:

self.valid_pairs?(pairings) => false ... because the last names in the pairings[0] are the same 

代碼

def self.valid_pairs?(pairings) 

validated_pairings = [] 
pairings.each do |p| 
    match1 = /(\w*)\s(\w*)|(\w*)\s(\w*)\s(\w*)/.match(p[0]).to_a 
    match2 = /(\w*)\s(\w*)|(\w*)\s(\w*)\s(\w*)/.match(p[1]).to_a 

    if match1.last != match2.last 
    validated_pairings << p 
    else 
    end 
end 

if validated_pairings == pairings 
    true 
else 
    false 
end 

end 
+0

你的正則表達式並沒有太大的意義,因爲這隻能匹配一個空白。你可以把一個樣本數據和你想要的輸出? – 2014-08-27 16:04:01

+0

我添加了樣本輸入和所需的輸出。我不確定這是否有幫助 - 這是我第一次發佈的問題,所以請告訴我,如果我誤解了您的請求。 – JHomann 2014-08-27 16:16:51

+0

我明白了,你想要做的就是比較姓氏。你需要的正則表達式是爲了獲取姓氏 – 2014-08-27 16:51:05

回答

0

您可以使用下面的正則表達式搶lastnames:

(\w+)$ 

Working demo

enter image description here

要想從捕獲組的內容,你可以這樣做:

lastname = /(\w+)$/.match(p[0]).captures 

因此,對於:

lastname = /(\w+)$/.match("Sarah Smith").captures 
// lastname => "Smith" 

我離開編碼到你

0

你並不需要一個正則表達式來獲取最後一個字,你可以使用split

match1 = p[0].split 
match2 = p[1].split 

您還可以通過使用簡化代碼很多all?

def self.valid_pairs?(pairings) 
    pairings.all? do |p1, p2| 
    p1.split.last != p2.split.last 
    end 
end 

上面的代碼返回true只有當所有的pairings數組中的元素由於兩個名稱沒有相同的姓氏而返回true。

0

它會少些混亂,如果你的方法是:

def any_matching_last_names?(pairings) 
    pairings.any? { |p1,p2| p1.last_name == p2.last_name } 
end 

其中last_name通過任何方式你喜歡的(例如,p.split.lastp[/\w+$/]pairings將是「有效的」,如果從p1p2提取姓氏。此方法返回false,所以你可能會使用這樣的:

list.add(pairings) unless any_matching_last_names?(pairings)