I have such code
reg = /(.+)_path/
if reg.match('home_path')
puts reg.match('home_path')[0]
end
This will eval regex twice 🙁
So…
reg = /(.+)_path/
result = reg.match('home_path')
if result
puts result[0]
end
But it will store variable result in memory till.
I have one functional-programming idea
/(.+)_path/.match('home_path').compact.each do |match|
puts match[0]
end
But seems there should be better solution, isn’t it?
There are special global variables (their names start with
$) that contain results of the last regexp match:You can find full list of predefined global variables here.
Note, that in the examples above
putswon’t be executed at all if you pass a string that doesn’t match the regexp.And speaking about general case you can always put assignment into condition itself:
Though, many people don’t like that as it makes code less readable and gives a good opportunity for confusing
=and==.