去除所有空白的Ruby函数是什么?我正在寻找一些类似于PHP的trim()?
当前回答
我个人倾向于使用.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"
其他回答
分裂。Join将丢弃字符串中任何位置的所有空格。
" a b c d ".split.join
> "abcd"
它很容易输入和记忆,所以在控制台和快速破解上都很不错。在严肃的代码中可能不受欢迎,因为它掩盖了意图。
(基于上文justice的回答中Piotr的评论)
gsub方法就可以了。 gsub方法可以在字符串上调用,并说:
a = "this is a string"
a = a.gsub(" ","")
puts a
#Output: thisisastring
gsub方法搜索第一个参数的每一次出现 然后用第二个参数替换它。在这种情况下,它将替换字符串中的每个空格并删除它。
另一个例子:
b = "the white fox has a torn tail"
我们把所有出现的字母t都换成大写的t
b = b.gsub("t","T")
puts b
#Output: The whiTe fox has a Torn Tail
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 >
"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)
这里有很多建议,但当我读到你的问题和说“删除所有空白”的具体行时,我想到的是:
" a b c " => "abc"
如果这确实是需要的,你可以做这个简单的操作
wide_string = " a b c "
narrow_string = wide_string.delete(" ")
# you can pass all the different kinds
# of whitespaces that you want to remove
puts narrow_string # => "abc"
推荐文章
- Printf与std::字符串?
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 如何在PHP中截断字符串最接近于一定数量的字符?
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- 为什么在Java和。net中不能修改字符串?
- 如何创建一个日期对象从字符串在javascript
- 如何测试参数是否存在在轨道