如果需要,如何使用 gsub 添加尾部斜杠
如果需要,我正在尝试添加尾部斜杠:
a = '/var/www'
a.gsub
...
我不知道该怎么做。
I'm trying to add trailing slash if needed:
a = '/var/www'
a.gsub
...
I don't know how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
快速、简单,并且具有保证
a
以路径分隔符结尾的效果;也就是说,无论a
是"/var/www"
还是"/var/www/"
,它都会给出相同的结果。这与上面 Joe White 的评论相同;我不知道他为什么不将其作为答案提交,因为它应该是一个答案。
奇怪的是,Pathname 库没有提供执行相同操作的便捷方法。
Swift, simple, and has the effect of guaranteeing that
a
ends in a path separator; that is, it gives the same result whethera
is"/var/www"
or"/var/www/"
.This is same as Joe White's comment above; I don't know why he didn't submit it as an answer, as it deserves to be one.
Oddly, the Pathname library doesn't provide a convenient way of doing the same thing.
这是一个更易读的版本
Here's a bit more readable version
为什么要使用gsub?
sub
而不是gsub
。sub!
或gsub!
。由于您没有进行替换,因此只需在需要时附加斜杠:
更新: 要使其与旧版本的 Ruby (1.8.x) 兼容,请稍微修改它:
Why do you want to use gsub?
sub
notgsub
.sub!
orgsub!
.Since you're not doing substitution, just append the slash if needed:
Update: To make it compatible with older versions of Ruby (1.8.x), modify it slightly:
您可以使用
.chomp('/')
删除可选的尾随/
,然后使用.concat('/')
附加再次斜线。You can use
.chomp('/')
to strip of the optionally trailing/
and then.concat('/')
to append a slash again.以下脚本显示了如何完成此操作:
它输出:
并通过用相同的字符加上尾随的
//
)来工作代码> 也是如此。The following script shows how this can be done:
It outputs:
and works by substituting the last character of the line (if it's not a
/
) with the same character plus a trailing/
as well.已经介绍了几种不同的方法,通过另一种方法进行混合:
或
值得注意的是,这两种方法都会将字符串中任何位置的任何 '//' 情况转换为 '/' ,但如果您只是处理路径,这不太可能引起问题。
There are a couple of different ways that have already been covered, to through another into the mix:
or
It's worth noting though that both of those will convert any cases of '//' to '/' anywhere in the string, though if you are just dealing with paths, that's unlikely to cause problems.
非常简单的 gsub,作为一个行比连接 (<<) 更容易,
这只是在字符串末尾找到一个可选的
/
字符并表示Pretty simple gsub, which is easier as a one liner than the concatenation (<<)
This simply finds an optional
/
character at the end of the string and rep