Reputation: 4078
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?
Upvotes: 1
Views: 754
Reputation: 2496
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)
Upvotes: 5