How to print a string with a backward slash in Ruby
Asked Answered
W

4

6

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

The IRB is giving me an unexpected output. Please find the same below:-

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

Any ideas on how can I get IRB to print the original string i.e. "xyz\123".

Thank you..

UPDATE :

I tried escaping it , but it doesn't seem to be that simple for some reason. Please find below my trials 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 > 
Wensleydale answered 10/4, 2012 at 4:53 Comment(2)
"Just escape it." Or, "read a tutorial". Take a pick. You may want .inspect as well.Cuttlefish
I wonder why this question was down voted..Wensleydale
O
5

UPDATED answer:

escape token '\' is always working in plain ruby code, but not always working in "ruby console". so I suggest you write a 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 result as:

hi\backslash

and see @pst's comment.

Osteoclasis answered 10/4, 2012 at 4:57 Comment(2)
I tried this, it doesn't work. It prints the backslash twice. Output: "xyz\\123"Wensleydale
@Wensleydale That is correct. See my comment under Hophat's answer.Cuttlefish
S
3

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

Smilax answered 10/4, 2012 at 4:57 Comment(3)
I tried this, it doesn't work. It prints the backslash twice. Output: "xyz\\123"Wensleydale
@Wensleydale Which is correct because the REPL prints the .inspect form which, for strings is the double-quoted form that can be "eval"ed back to an equivalent of the original object. Try: puts str and compare.Cuttlefish
@pst Thanks.. works now.. so its just that in Rails Console and IRB .. it wouldn't print as it does with "puts str" ?Wensleydale
A
0

How to print a backslash?

Use 2 backslashes, e.g. "xyz\\123"

Why does "xyz\123" evaluate 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 83
= ASCII S

Autolysin answered 20/7, 2014 at 2:30 Comment(1)
how does this relate to printing a backslash?Grillage
F
-1

It's simple ... try dump function:

mystring = %Q{"Double Quotes"}
p mystring.dump
=> "\"\\\"Double Quotes\\\"\""
p mystring
=>"\"Double Quotes\""
Fungus answered 8/11, 2016 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.