简体   繁体   中英

How to print backslash in single quoted string in ruby

I have the following string in ruby version 2.3.3:

'\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x01u\x00\x00\x01u\b'

I would like to compare it to another string. However, the following occurs:

x = '\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x01u\x00\x00\x01u\b'
 => "\\x89PNG\\r\\n\\x1A\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x01u\\x00\\x00\\x01u\\b"

Where the addition of the extra slash messes up the comparison. Equally confusing, the following happens:

 x.gsub("\\\\", "\\")
 => "\\x89PNG\\r\\n\\x1A\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x01u\\x00\\x00\\x01u\\b"

I have tried double quoting the string, using %{} and %Q[]. None of them simply store the string without interpreting escape sequences. How do I store this string without altering it?

So long as the strings share the same encoding, byte comparison would be elegant solution without the need for additional escaping.

str.bytes == other.bytes

To display a backslash, you simply escape it with a single backslash:

puts '\\'
\

Additionally, depending on your exact usage, could use the <=> operator:

(str <=> other).zero?

EDIT

To expand a little more, there is a difference in what is displayed to you if you just did something like this:

a = '\\'
p a
=> '\\'

This will show itself as two backslashes, but it is still in fact a single character, not two.

a = '\\'
a.bytes
=> [92] # ASCII code for a backslash (single byte)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM