Actions
Bug #19932
closedRegexp o modifier freeze interpolation between method calls
Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-linux]
Description
Taken the following PoC:
def poc(regexp)
hs = [
'azerty',
'azertyui',
'azertyuiop'
]
out = []
hs.each do |h|
out << h if /#{regexp}/.match?('azerty')
end
out
end
p poc('az')
p poc('wxc')
I have the following output:
["azerty", "azertyui", "azertyuiop"]
[]
Now because the regexp never change inside the method once set I could add the o
modifier so that #{}
interpolation is computed only once.
So the PoC becomes:
def poc(regexp)
hs = [
'azerty',
'azertyui',
'azertyuiop'
]
out = []
hs.each do |h|
out << h if /#{regexp}/o.match?('azerty')
end
out
end
p poc('az')
p poc('wxc')
Output:
["azerty", "azertyui", "azertyuiop"]
["azerty", "azertyui", "azertyuiop"]
So each future call to the method will be equals to the result of the first call because the regexp is "frozen".
I was expecting the regexp to be "frozen" only for the current call in an effort of performance but instead it's "frozen" for future calls too.
Another example of usage of o
modifier here: https://learnbyexample.github.io/Ruby_Regexp/modifiers.html#o-modifier
So is that a side effect or is that the expected behavior?
Actions
Like1
Like0Like0Like1Like1