我(非常)是Ruby的新手,无法弄清楚为什么我的rspec会挂起。我在下面给出的方法中有两个正则表达式。如果我注释掉,rspec也可以。但如果两者都存在,则rspec挂起(link to full project, including tests,如果它有助于提供上下文)
示例输入:
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 :(得分:0)
您可以使用以下正则表达式获取姓氏:
(\w+)$
<强> Working demo
要从捕获组中获取内容,您可以执行以下操作:
lastname = /(\w+)$/.match(p[0]).captures
所以,对于:
lastname = /(\w+)$/.match("Sarah Smith").captures
// lastname => "Smith"
我留下编码给你
答案 1 :(得分: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
只有当pairings
数组中的所有元素都返回true而且两个名称的姓氏不同时,上述代码才返回true。
答案 2 :(得分:0)
如果您的方法是:
,那就不那么容易混淆了def any_matching_last_names?(pairings)
pairings.any? { |p1,p2| p1.last_name == p2.last_name }
end
其中last_name
以您喜欢的方式从p1
和p2
中提取姓氏(例如p.split.last
或p[/\w+$/]
。pairings
如果此方法返回false
,则为“有效”,因此您可以像这样使用它:
list.add(pairings) unless any_matching_last_names?(pairings)