SirLenz0rlot SirLenz0rlot - 13 days ago 5
Ruby Question

When Ruby regex doesn't fit on line

When I have a very long regex, like a cucumber step definition, what would be the best way to line wrap it?

example, i would like something like:

When /^I have a very long step definition here in my step definition file$/ do
...
end


break up into two lines (this doesnt work:)

When /^I have a very long step definition here in /\
/my step definition file$/ do
...
end

Answer

You can use a verbose regex with the /x modifier, but then you need to make spaces explicit because they will otherwise be ignored. Another advantage is that this allows you to comment your regex (which, if it's long, might be a good idea):

/^                               # Match start of string
I[ ]have[ ]a[ ]very[ ]long[ ]
step[ ]definition[ ]here[ ]
in[ ]my[ ]step[ ]definition[ ]file
$                               # Match end of string
/x
Comments