【发布时间】:2019-04-28 15:41:41
【问题描述】:
我正在尝试使用array.select 从字符串数组中排除元素。我有这个方法:
def filter_out_other_bad_vals(array_of_strs, things_i_want)
array_of_strs = array_of_strs.select { |line| /"#{things_i_want}"/.match(line) }
end
我想将字符串作为变量things_i_want 传递。但这不会返回任何匹配项:
array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
pattern = 'want_this'
array = filter_out_other_bad_vals(array, pattern)
这将返回一个空数组。但是如果我硬编码匹配表达式中的值,我会得到我想要的。
def filter_out_other_bad_vals(array_of_strs, things_i_want)
array_of_strs = array_of_strs.select { |line| /want_this/.match(line) }
end
如何在正则表达式中添加变量?我究竟做错了什么?
我可以遍历数组,检查每个项目,然后将值保存在另一个数组中,但这不太像 ruby,是吗?
【问题讨论】:
-
如果您想根据正则表达式进行过滤(给定的问题不清楚),那么您可以使用
array.grep(/want_this/)或pattern = /want_this/后跟array.grep(pattern)... 获取匹配元素以外的内容,使用grep_v而不是grep