去除所有空白的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"
其他回答
我个人倾向于使用.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"
别忘了:
$ s = " I have white space ".split
=> ["I", "have", "white", "space"]
你可以试试这个:
"ab c d efg hi ".split.map(&:strip)
为了得到这个:
["ab, "c", "d", "efg", "hi"]
或者如果你想要一个字符串,只需使用:
"ab c d efg hi ".split.join
我试图这样做,因为我想使用记录“标题”作为视图中的id,但标题有空格。
解决方案是:
record.value.delete(' ') # Foo Bar -> FooBar
我有点晚了,但是我使用strip!来删除尾随和前导空格。如果您有一个数组,就像我所做的那样,我需要遍历该数组并在实例结束后保存它。!搞定了这个。这删除了结尾或开头的所有空格,而不仅仅是第一个前导或最后一个尾随。
例如:
array = ["hello "," Melanie", "is", " new ", "to ", " programming"]
array.each do |i|
i.strip!
end
这将输出到:["hello","Melanie", "is", "new "," to", "programming"]。我在一个视频中进一步探讨/分享了这个问题,以突出这个代码来回答我遇到的类似问题。
我是较新的编程和使用strip不工作,因为它没有保存到循环结束后的数组。
推荐文章
- Ruby中“or”和||的区别?
- 为什么在Java和。net中不能修改字符串?
- 如何创建一个日期对象从字符串在javascript
- 如何测试参数是否存在在轨道
- 在Android上将字符串转换为整数
- 删除字符串的最后3个字符
- 如何大写一个字符串的第一个字母在省道?
- 不区分大小写的列表排序,没有降低结果?
- indexOf()和search()的区别是什么?
- 我如何在Swift连接字符串?
- 如何获得一个变量值,如果变量名存储为字符串?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- 为什么不是字符串。空一个常数?
- RVM不是一个函数,用' RVM use…’不会起作用
- 如何删除表中特定列的第一个字符?