简体   繁体   English

如何在Ruby中的单引号字符串中打印反斜杠

[英]How to print backslash in single quoted string in ruby

I have the following string in ruby version 2.3.3: 我在ruby 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[]. 我尝试使用%{}和%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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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