2014-10-05 56 views
1

下面的代码行正确地从一个下拉列表中选择“李四”:如何将正则表达式作为参数传递给函数?

browser.select_list(:id => "ListOwnerID").option(:text => /Joe Bloggs/).select # edited: added '.select' 

我如何通过所有者的名称作为变量“LIST_OWNER”?

喜欢的东西:

def set_list_owner(list_owner) 
    browser.select_list(:id => "ListOwnerID").option(:text => /list_owner/).select 
end 

用法:

set_list_owner("Joe Bloggs") 

回答

3

您可以使用Regexp::new

re_string = '\d' 
Regexp.new(re_string) =~ 'abc 123' 
# => 4 

替代卡里Swoveland建议(正则表达式插值):

/#{re_string}/ 

def set_list_owner(list_owner) 
    browser.select_list(:id => "ListOwnerID").option(:text => Regexp.new(list_owner)) 
end 

set_list_owner("Joe Bloggs") 

如果你想字符串字面匹配,而不是解释为正则表达式,使用Regexp::escape

Regexp.new(Regexp.escape(list_owner)) 
+1

另外'正则表达式= /#{re_string}/=>/\ d /'。 – 2014-10-05 18:00:12

+0

@CarySwoveland,尼斯解决方案。我添加了您的替代答案。谢谢。 – falsetru 2014-10-05 18:03:59

+0

我用'Regexp.new(list_owner)'。至少,我可以理解:) – OldGrantonian 2014-10-05 18:19:32

相关问题