$ 1 and \ 1 in Ruby

When using regular expressions in Ruby, what is the difference between $ 1 and \ 1?

+46
ruby regex
Nov 13 '08 at 22:30
source share
2 answers

\ 1 is a backlink that will work in only one sub or gsub method call, for example:

 "foobar".sub(/foo(.*)/, '\1\1') # => "barbar" 

$ 1 is a global variable that can be used in later code:

 if "foobar" =~ /foo(.*)/ then puts "The matching word was #{$1}" end 

Output:

 "The matching word was bar" # => nil 
+77
Nov 13 '08 at 22:37
source share

Remember that there is a third option, the block form sub . Sometimes you need it. Suppose you want to replace some text with reverse text. You cannot use $ 1 because it is not bound fast enough:

 "foobar".sub(/(.*)/, $1.reverse) # WRONG: either uses a PREVIOUS value of $1, # or gives an error if $1 is unbound 

You also cannot use \1 , because the sub method just does the text substitution \1 with the corresponding captured text, there is no magic here:

 "foobar".sub(/(.*)/, '\1'.reverse) # WRONG: returns '1\' 

So, if you want to do something interesting, you should use the sub block form ($ 1, $ 2, $ `, $ ', etc.):

 "foobar".sub(/.*/){|m| m.reverse} # => returns 'raboof' "foobar".sub(/(...)(...)/){$1.reverse + $2.reverse} # => returns 'oofrab' 
+29
Nov 13 '08 at 23:01
source share



All Articles