Search code examples
rubyregexblock

Will a block run if it is passed nil as a parameter in Ruby?


I have the following block in a ruby script:

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

If /aPattern/ does not match anything in line, will the block still run? And if not, is there a way I can force it to run?


Solution

  • 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.