简体   繁体   English

使用gsub替换Ruby中的双斜杠

[英]Using gsub to replace double slashes in Ruby

I am having some issues using gsub to replace double slashes. 我在使用gsub替换双斜杠时遇到了一些问题。 The problem is this: 问题是这样的:

I built a small script to parse YAML files for a directory location, and then to use that to glob the files in that directory. 我构建了一个小脚本来解析目录位置的YAML文件,然后使用该脚本来遍历该目录中的文件。 Say this is the directory it finds: 说这是它找到的目录:

C:\Program Files\Adobe\Adobe Flash CS3\en\Configuration\ActionScript 3.0\Classes

This is a Windows directory, and the backslashes are escaped by YAML parser, so this really gets loaded from parser as: 这是Windows目录,YAML解析器对反斜杠进行了转义,因此它实际上是从解析器加载为:

C:\\Program Files\\Adobe\\Adobe Flash CS3\\en\\Configuration\\ActionScript 3.0\\Classes

To use this directory, I wanted to gsub away these double slashes: 要使用此目录,我想用gsub除去这些双斜杠:

path.gsub('\\','/')

This call replaced most of the double backslashes in the path, though the script still did not work. 尽管脚本仍然无法运行,但此调用替换了路径中的大多数双反斜杠。 When I looked at what the path had become, I found that there was still one backslash that had not been replaced by gsub: 当我查看路径变成什么时,我发现还有一个反斜杠尚未被gsub取代:

\en

What explains this strange behavior? 是什么解释了这种奇怪的行为?

Seems to work fine on my end. 看来对我来说还不错。

irb(main):001:0> string = "C:\\Program Files\\Adobe\\Adobe Flash CS3\\en\\Configuration\\ActionScript 3.0\\Classes"
=> "C:\\Program Files\\Adobe\\Adobe Flash CS3\\en\\Configuration\\ActionScript 3.0\\Classes\n"
irb(main):003:0> string.gsub('\\', '/')
=> "C:/Program Files/Adobe/Adobe Flash CS3/en/Configuration/ActionScript 3.0/Classes\n"

What version of Ruby are you using? 您正在使用哪个版本的Ruby? Perhaps something else is going on in the script? 脚本中可能还有其他情况吗? Because it works fine in irb for me. 因为它对irb来说对我来说效果很好。

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

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