Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a string with a backward slash in Ruby

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 > 
like image 470
boddhisattva Avatar asked Apr 10 '12 04:04

boddhisattva


2 Answers

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.

like image 71
Siwei Avatar answered Oct 10 '22 07:10

Siwei


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".

like image 36
Hophat Abc Avatar answered Oct 10 '22 09:10

Hophat Abc