【问题标题】:Will a block run if it is passed nil as a parameter in Ruby?如果在 Ruby 中将块作为参数传递 nil,它会运行吗?
【发布时间】:2023-04-04 11:42:01
【问题描述】:

我在 ruby​​ 脚本中有以下块:

for line in allLines
    line.match(/aPattern/) { |matchData|
        # Do something with matchData
    }
end

如果/aPattern/ 与行中的任何内容都不匹配,该块还会运行吗?如果没有,有没有办法强制它运行?

【问题讨论】:

  • 从文档 (ruby-doc.org/core-1.9.3/String.html#method-i-match) 看来,如果没有匹配,则不会调用该块:“如果给出了一个块,如果匹配成功,则使用 MatchData 调用该块,这样你可以写”。请问如果没有匹配,你为什么要运行它?

标签: ruby regex block


【解决方案1】:

答案是否定的,如果匹配不成功,匹配块将不会运行。但是,for 通常不会在 Ruby 中使用,each 更习惯用法,例如:

allLines.each do |line|
  if line =~ /aPattern/
    do_thing_with_last_match($~) ## $~ is last match
  else
    do_non_match_thing_with_line
  end
end

注意,=~ 是一个正则表达式匹配运算符。

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2016-02-27
    • 2011-01-28
    • 2011-01-28
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多