开发者

How can I iterate over array elements matching a regular expression?

Is there a method that can be used with "each" to filter array elements depending on a regular expression matching?

I have for example the following array:

arr = ["one", "has_two", "has_tree", "four"]

I want to loop into this array and to take only elements beginning with "has".

t开发者_如何学Pythonhe following code is doing the loop for all the elements

arr.each |element| do

....

end


You can use Enumerable's grep method to do this:

arr.grep(/^has/).each do |element|
  ...
end


You can select the elements you're interested in, and then loop over those:

arr.select { |e| e[/^has/] }.each do |element|


end


I'd say:

arr.find_all{|el| el =~ /^has/}.each do...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜