Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 669 Vote(s) - 3.58 Average
  • 1
  • 2
  • 3
  • 4
  • 5
$1 and \1 in Ruby

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

#2
\1 is a backreference which will only work in the same `sub` or `gsub` method call, e.g.:

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

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

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

Output:

"The matching word was bar"
# => nil
Reply

#3
Keep in mind there's a third option, the block form of `sub`. Sometimes you need it. Say you want to replace some text with the reverse of that text. You can't use $1 because it's not bound quickly enough:

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

You also can't use `\1`, because the `sub` method just does a simple text-substitution of `\1` with the appropriate captured text, there's no magic taking place here:

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

So if you want to do anything fancy, you should use the block form of `sub` ($1, $2, $`, $' etc. will be available):

"foobar".sub(/.*/){|m| m.reverse} # => returns 'raboof'
"foobar".sub(/(...)(...)/){$1.reverse + $2.reverse} # => returns 'oofrab'
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through