Ruby函數刪除全部空格?

刪除全部空格的Ruby函數是什麼? 有點像php的trim()php


#1樓

s = "I have white space".delete(' ')

並模擬PHP的trim()函數: api

s = "   I have leading and trailing white space   ".strip

#2樓

相關回答: 框架

"   clean up my edges    ".strip

回報 函數

"clean up my edges"

#3樓

也別忘了: ui

$ s = "   I have white space   ".split
=> ["I", "have", "white", "space"]

#4樓

若是你只想刪除前導和尾隨空格(好比PHP的修剪)你可使用.strip ,可是若是要刪除全部空格,你可使用.gsub(/\\s+/, "")代替。 spa


#5樓

Ruby的.strip方法執行與trim()至關的PHP。 code

要刪除全部空格: ip

"  leading    trailing   ".squeeze(' ').strip
=> "leading trailing"

@Tass讓我知道個人原始答案連續刪除了重複的字母 - 你好! 我已經改用了squish方法,若是使用Rails框架,這種方法更聰明。 get

require 'active_support/all'
"  leading    trailing   ".squish
=> "leading trailing"

"  good    men   ".squish
=> "good men"

引用: http//apidock.com/rails/String/squish it

相關文章
相關標籤/搜索