'Use Ruby's heredoc syntax to read a regular expression

In my tests, I have a - somewhat longer, multi-line - HTML response containing a date and time. I thought I could use assert_match to compare the expected result '\d{4}-\d{2}-\d{2} \d{2}:\d{2}' with the actual result 'yyyy-mm-dd hh:mm':

assert_match <<END_OF_TEXT, response.body
...
... as at: \d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC
...
END_OF_TEXT

Somehow, it does not seem to be possible to use this syntax to input a regular expression, even using the various possible delimiters for END_OF_TEXT.



Solution 1:[1]

The following works nicely:

p = Regexp.new <<'END_OF_TEXT'
...
... as at: \d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC
...
END_OF_TEXT
assert_match p, response.body

Solution 2:[2]

Use the Regexp "extended" mode, which enables Freespacing and Comments:

assert_match(/\A
  [[:digit:]]+ # 1 or more digits before the decimal point
  (\.          # Decimal point
    [[:digit:]]+ # 1 or more digits after the decimal point
  )? # The decimal point and following digits are optional
\Z/x,
'3.14')

Note that this causes the regular expression to ignore the natural newlines that appear in the literal, so if you want it to match a newline, you need specify it in the pattern with \n.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wribln
Solution 2