Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Use condition result in condition block

Tags:

regex

ruby

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?

like image 930
everm1nd Avatar asked Jun 30 '26 19:06

everm1nd


1 Answers

There are special global variables (their names start with $) that contain results of the last regexp match:

r = /(.+)_path/

# $1 - the n-th group of the last successful match (may be > 1)
puts $1 if r.match('home_path')
# => home 

# $& - the string matched by the last successful match
puts $& if r.match('home_path')
# => home_path

You can find full list of predefined global variables here.

Note, that in the examples above puts won'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:

if m = /(.+)_path/.match('home_path')
  puts m[0]
end

Though, many people don't like that as it makes code less readable and gives a good opportunity for confusing = and ==.

like image 81
KL-7 Avatar answered Jul 03 '26 07:07

KL-7