Ruby:如何剥离字符串并删除空白?
给定一个字符串,我想去掉它,但我想去掉前后的空格。例如:Ruby:如何剥离字符串并删除空白?,ruby,string,whitespace,strip,Ruby,String,Whitespace,Strip,给定一个字符串,我想去掉它,但我想去掉前后的空格。例如: my_strip(" hello world ") # => [" ", "hello world", " "] my_strip("hello world\t ") # => ["", "hello world", "\t "] my_strip("hello world") # => ["", "hello world", ""] 您将如何实现my_strip?我将使用regexp:
my_strip(" hello world ") # => [" ", "hello world", " "]
my_strip("hello world\t ") # => ["", "hello world", "\t "]
my_strip("hello world") # => ["", "hello world", ""]
您将如何实现my_strip?我将使用regexp:
def my_strip( s )
a = s.split /\b/
a.unshift( '' ) if a[0][/\S/]
a.push( '' ) if a[-1][/\S/]
[a[0], a[1..-2].join, a[-1]]
end
def my_strip(s)
s =~ /(\s*)(.*?)(\s*)\z/
*a = $1, $2, $3
end
这是我提出的一个解决方案:
def my_strip(s)
s.match(/\A(\s*)(.*?)(\s*)\z/)[1..3]
end
但是,我想知道是否还有其他(可能更有效的)解决方案。解决方案
def my_strip(str)
str.match /\A(\s*)(.*?)(\s*)\z/m
return $1, $2, $3
end
测试套件(RSpec)
my_strip(“hello”)#=>[,“hello”,“]
a=$1、$2、$3和a=$1、$2、$3
之间的区别是什么?@Misha Moroshko-修复了上述问题。我不确定所问的区别。IMPO,SPLAT运算符可以清楚地创建一个数组。有趣的是,你甚至可以做<代码> *$ 1,2美元,3美元< /代码>(至少在1.92)@菲利普:现在:<代码> MyILASH(“Hello World”)< /> > >“=”>“”,“Hello”,“”在Word边界上的分裂会引起问题,考虑一个字符串“…”,它没有单词边界。谢谢你的提示(锚是你的朋友)。哈哈,和我想到的完全一样,只是我添加了多行标志。
describe 'my_strip' do
specify { my_strip(" hello world ").should == [" ", "hello world", " "] }
specify { my_strip("hello world\t ").should == ["", "hello world", "\t "] }
specify { my_strip("hello world").should == ["", "hello world", ""] }
specify { my_strip(" hello\n world\n \n").should == [" ", "hello\n world", "\n \n"] }
specify { my_strip(" ... ").should == [" ", "...", " "] }
specify { my_strip(" ").should == [" ", "", ""] }
end
def my_strip(str)
sstr = str.strip
[str.rstrip.sub(sstr, ''), sstr, str.lstrip.sub(sstr, '')]
end