How to print a backslash string in Ruby

I have the string str = "xyz\123" and I want to print it as is.

IRB gives me an unexpected result. Please find the same: -

 1.9.2p290 :003 > str = "xyz\123" => "xyzS" 1.9.2p290 :004 > 

Any ideas on how I can get IRB to print the original line, that is, "xyz \ 123".

Thanks..

UPDATE :

I tried to slip away from him, but for some reason this does not seem so simple. Below are my tests with the same:

 1.9.2p290 :004 > str = "xyz'\'123" => "xyz''123" 1.9.2p290 :005 > str = "xyz'\\'123" => "xyz'\\'123" 1.9.2p290 :006 > str = "xyz'\\\'123" => "xyz'\\'123" 1.9.2p290 :007 > 
+6
source share
4 answers

UPDATED answer:

escape token '\' always works in plain ruby ​​code, but doesn't always work in "ruby console". so I suggest you write unit test:

 # escape_token_test.rb require 'test/unit' class EscapeTokenTest < Test::Unit::TestCase def test_how_to_escape hi = "hi\\backslash" puts hi end end 

and you will get the result as:

 hi\backslash 

and see @pst comment.

+5
source

The backslash character is an escape character. You may have seen that "\ n" is used to display a new line, and that is why. "\ 123" evaulates the ASCII code for 83, which is an "S". To print a backslash, use a backslash. Therefore, you can use str = "xyz\\123" .

+3
source

How to print backslash?

Use 2 backslashes, for example. "xyz\\123"

Why is "xyz\123" rated to "xyzS" ?

In a double-quoted string, \nnn is an octal escape .

Table 22.2. Substitutions in Double-Quoted Strings

Thomas, D. (2009) Programming Ruby, p.329

So octal 123
= (64 * 1) + (8 * 2) + 3
= decimal digit 83
= ASCII S

0
source

It's just ... try the dump function:

 mystring = %Q{"Double Quotes"} p mystring.dump => "\"\\\"Double Quotes\\\"\"" p mystring =>"\"Double Quotes\"" 
0
source

Source: https://habr.com/ru/post/912813/


All Articles