Bug #17110
closedString.tr unexpected behaviour with backslash
Description
"\\".tr("\\","A") works great, with "\\" becoming "A".
"\\".tr("\\C","AB") should also output "A", but instead outputs "\\".
Updated by theplen (Joey Sheets) about 5 years ago
"\\".tr("\\","A") works great, with "\\" becoming "A"
"\\".tr("\\C","AB") should also output "A" but instead outputs "\\"
Updated by sawa (Tsuyoshi Sawada) about 5 years ago
- Description updated (diff)
Updated by mame (Yusuke Endoh) about 5 years ago
- Status changed from Open to Rejected
See the document.
The backslash character
\can be used to escape^or-and is otherwise ignored unless it appears at the end of a range or the end of the from_str or to_str:
https://docs.ruby-lang.org/en/2.7.0/String.html#method-i-tr
So you can write "\\".tr("C\\", "BA") according to the document.
This seems undocumented, but \ can be used to escape \, so you can also write "\\".tr("\\\\C", "AB").
Updated by theplen (Joey Sheets) about 5 years ago
Is there no way to do change all backslashes to forward slashes and forward slashes to backslashes in the same tr command?
# Should result in "/\\" but instead results in "\\/" (unchanged)
"\\/".tr("\//","\\/")
Updated by mame (Yusuke Endoh) about 5 years ago
p "\\/".tr("/\\\\", "\\\\/") #=> "/\\"
Unfortunately it is complicated, but \ is an escape character of string literal as well as an escape character of String#tr format, so it is unavoidable.
Updated by theplen (Joey Sheets) about 5 years ago
Yusuke Endoh, thanks for clearing it up.