Ruby删除空格?

时间:2014-05-08 22:41:49

标签: ruby

删除 空格时遇到一些问题。

vehicle = [" 2013 ", "BMW ", "535 ", "Sedan 4 Door "] 
v = vehicle[0]
# => " 2013 "

v[-1].ord.chr
# => "\xA0"

尝试失败:

vehicle.map { |d| d.gsub(/\S(\w*)/, '\1') }
# => ["2013", "MW", "35", "edan  oor"] (space gone but so are other characters.)

vehicle.map { |d| d.gsub(/\xA0/, '') }
# => SyntaxError: (irb):340: invalid multibyte escape: /\xA0/

vehicle.map { |d| d.gsub(/#{160.chr}/, '') }
# => Encoding::CompatibilityError: incompatible encoding regexp match (ASCII-8BIT regexp with UTF-8 string)

来自this question的答案:

vehicle.map { |d| d.gsub("\302\240", ' ').strip }
# => ["2013", "BMW", "535", "Sedan 4 Door"] 

但它没有解释原因/方式。有人可以解释这是如何以及为什么有效?或建议另类?

1 个答案:

答案 0 :(得分:3)

可能只需使用/[[:space:]]/来匹配所有空格(unicode or not)。

\302\240只是utf8编码的代表。

相关问题