去除所有空白的Ruby函数是什么?我正在寻找一些类似于PHP的trim()?
当前回答
Ruby的String的.scan()和.join()方法也可以帮助克服字符串中的空白。
扫描(\ w + /)。Join将删除所有空格并连接字符串
string = "White spaces in me".scan(/\w+/).join
=>"Whitespacesinme"
它还从字符串的左右部分删除空格。表示ltrim, rtrim和trim。以防万一有人有C, FoxPro或Visual Basic的背景,然后跳到Ruby。
2.1.6:002 > string = " White spaces in me ".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:003 > string = " White spaces in me".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:004 > string = "White spaces in me ".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:005 >
其他回答
我个人倾向于使用.tr方法
如:
string = "this is a string to smash together"
string.tr(' ', '') # => "thisisastringtosmashtogether"
感谢@FrankScmitt指出,要删除所有空白(不仅仅是空格),你需要这样写:
string = "this is a string with tabs\t and a \nnewline"
string.tr(" \n\t", '') # => "thisisastringwithtabsandanewline"
"1232 23 2 23 232 232".delete(' ')
=> "123223223232232"
删除工作更快=)
user system total real
gsub, s 0.180000 0.010000 0.190000 (0.193014)
gsub, s+ 0.200000 0.000000 0.200000 (0.196408)
gsub, space 0.220000 0.000000 0.220000 (0.222711)
gsub, join 0.200000 0.000000 0.200000 (0.193478)
delete 0.040000 0.000000 0.040000 (0.045157)
现在说这个有点晚了,但是任何在谷歌上搜索这个页面的人都可能对这个版本感兴趣
如果你想清理一大块预先格式化的文本,用户可能以某种方式剪切和粘贴到你的应用程序,但保留单词间距,试试这个:
content = " a big nasty chunk of something
that's been pasted from a webpage or something and looks
like this
"
content.gsub(/\s+/, " ").strip
#=> "a big nasty chunk of something that's been pasted from a webpage or something and looks like this"
s = "I have white space".delete(' ')
并模拟PHP的trim()函数:
s = " I have leading and trailing white space ".strip
我会用这样的方法:
my_string = "Foo bar\nbaz quux"
my_string.split.join
=> "Foobarbazquux"
推荐文章
- 不区分大小写的列表排序,没有降低结果?
- indexOf()和search()的区别是什么?
- 我如何在Swift连接字符串?
- 如何获得一个变量值,如果变量名存储为字符串?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- 为什么不是字符串。空一个常数?
- RVM不是一个函数,用' RVM use…’不会起作用
- 如何删除表中特定列的第一个字符?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 将整数转换为字符串,以逗号表示千
- 将JavaScript字符串中的多个空格替换为单个空格
- printf()和puts()在C语言中的区别是什么?
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?