Project

General

Profile

Actions

Bug #17110

closed

String.tr unexpected behaviour with backslash

Added by theplen (Joey Sheets) almost 2 years ago. Updated almost 2 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
ruby -v:
ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x64-mingw32]
[ruby-core:99528]

Description

"\\".tr("\\","A") works great, with "\\" becoming "A".

"\\".tr("\\C","AB") should also output "A", but instead outputs "\\".

Updated by theplen (Joey Sheets) almost 2 years ago

"\\".tr("\\","A") works great, with "\\" becoming "A"

"\\".tr("\\C","AB") should also output "A" but instead outputs "\\"
Actions #2

Updated by sawa (Tsuyoshi Sawada) almost 2 years ago

  • Description updated (diff)

Updated by mame (Yusuke Endoh) almost 2 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) almost 2 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) almost 2 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) almost 2 years ago

Yusuke Endoh, thanks for clearing it up.

Actions

Also available in: Atom PDF