Ruby Okay, I want to remove a more than one space character in a strings if there's any. What I mean is, let's say I have a text like this:
如果有的话,我想在字符串中移除一个以上的空格字符。我的意思是,假设我有这样一个文本:
I want to learn ruby more and more.
See there's a more than one space character after "to" and before "learn" either it a tab or just a several spaces. Now what I want is, how can I know if there's something like this in a text file, and I want to make it just one space per word or string. So it will become like this
在“to”之后和“learn”之前有一个以上的空格字符,可以是一个制表符,也可以是几个空格。现在我想要的是,我怎么知道文本文件中是否有这样的东西,我想让它每个字或字符串只有一个空格。它会变成这样
I want to learn ruby more and more.
Can I use Gsub? or do I need to use other method? I tried Gsub, but can't figure out how to implement it the right way so it can produce the result I want. Hopefully I explained it clear. Any help is appreciated, thanks.
我可以用Gsub吗?还是我需要用别的方法?我尝试了Gsub,但是我不知道如何正确地实现它,这样它就可以产生我想要的结果。希望我解释清楚了。感谢您的帮助。
2 个解决方案
#1
5
You can use gsub
to replace one or more whitespace (regex / +/
) to a single whitespace:
您可以使用gsub将一个或多个空格(regex / +/)替换为单个空格:
'I want to learn ruby more and more.'.gsub(/ +/, " ")
#=> "I want to learn ruby more and more."
#2
5
String#squeeze remove runs of more than one character:
挤压删除一个以上字符的运行:
'I want to learn ruby more and more.'.squeeze(' ')
# => "I want to learn ruby more and more."
#1
5
You can use gsub
to replace one or more whitespace (regex / +/
) to a single whitespace:
您可以使用gsub将一个或多个空格(regex / +/)替换为单个空格:
'I want to learn ruby more and more.'.gsub(/ +/, " ")
#=> "I want to learn ruby more and more."
#2
5
String#squeeze remove runs of more than one character:
挤压删除一个以上字符的运行:
'I want to learn ruby more and more.'.squeeze(' ')
# => "I want to learn ruby more and more."