我在 ruby 脚本中有以下块:
for line in allLines
line.match(/aPattern/) { |matchData|
# Do something with matchData
}
end
如果/aPattern/
与行中的任何内容都不匹配,该块还会运行吗?如果没有,有没有办法可以强制它运行?
The answer is no, the match block will not be run if the match does not suceed. However, for
is generally not used in Ruby anyways, each
is more idiomatic, like:
allLines.each do |line|
if line =~ /aPattern/
do_thing_with_last_match($~) ## $~ is last match
else
do_non_match_thing_with_line
end
end
Note, =~
is a regex match operator.