Escape status in string literal as argument `String # tr`

There is something cryptic to me about the backslash escape status in one quoted string literal as an argument String#tr. Can you explain the contrast between the three examples below? In particular, I do not understand the second. To avoid complications, I use 'd'here, which does not change the value when escaping in double quote ( "\d"= "d").

'\\'.tr('\\', 'x')      #=> "x"
'\\'.tr('\\d', 'x')     #=> "\\"
'\\'.tr('\\\d', 'x')    #=> "x"
+5
source share
1 answer

Exit from tr

tr , . ^ , ( , ), , . a-f, . , , - ^ .

print 'abcdef'.tr('b-e', 'x')  # axxxxf
print 'abcdef'.tr('b\-e', 'x') # axcdxf

Ruby

, Ruby , , .. .

# Single quotes
print '\\'    # \
print '\d'    # \d
print '\\d'   # \d
print '\\\d'  # \\d

# Double quotes
print "\\"    # \
print "\d"    # d
print "\\d"   # \d
print "\\\d"  # \d

, .

'\\'.tr('\\', 'x')      #=> "x"

, '\\', \, . .

'\\'.tr('\\d', 'x')     #=> "\\"

, '\\d', \d. tr, , , d. : tr d x.

'\\'.tr('\\\d', 'x')    #=> "x"

, '\\\d', \\d. \\ \. \d \d, .. . ( , , d)

\\d tr , , d .

+9

All Articles