user3566591
user3566591

Reputation: 165

Ruby Single BackSlash Stored in Variable

\I have the following path: E:\Path\Reports.

If i want to store this path in a variable in ruby, i need to use "\\":

$location = "E:\\Path\\Reports"

Is there a way to avoid using the "\\" in the variable and still have the right path?

Upvotes: 0

Views: 141

Answers (4)

knrz
knrz

Reputation: 1811

An easier way would be to use File.join. It'll use / but Ruby will take care of converting that to \ under the hood on Windows.

$location = File.join('E', 'Path', 'Reports')
# $location is actually 'E/Path/Reports' now,
# but Ruby knows to convert the '/' to '\' on Windows.

This also has the benefit of making your code OS-independent.

Upvotes: 1

AGS
AGS

Reputation: 14498

You can use the %q:

$location = %q{E:\Path\Reports}

=> $location
"E:\\Path\\Reports"

=> puts $location
E:\Path\Reports

Upvotes: 1

nPn
nPn

Reputation: 16738

if you use this

location = 'E:\path\Reports'

it will be automatically escaped for you

Upvotes: 1

August
August

Reputation: 12558

Single-quoted strings interpret \ as a literal character, rather than an escape character (except for \', which is ' literally):

$location = 'E:\Path\Reports'

Upvotes: 0

Related Questions