Strip 在 rails 中无法正常工作
Strip not working properly in rails
我有一个字符串
s = " \r\n Displays the unique ID number assigned to the\r\nAlias Person."
我想删除这个开头 space 但它甚至连这些引号也没有删除。
我试过了
s = s.strip!
s = s.gsub!('"','')
代码没有问题。如果您试图从字符串的开头和结尾删除引号,它不会被删除。这就是 ruby 表示字符串的方式。尝试用这样的单引号定义一个字符串:-
2.4.2 :005 > str = 'aaa'
=> "aaa"
您的字符串中的内容是不间断的空格,如果您不在编辑器中使用任何帮助,区别是不可见的:
p " \r\n Displays the unique ID number assigned to the\r\nAlias Person."
p " \r\n Displays the unique ID number assigned to the\r\nAlias Person."
但是如果您映射字符串中的每个字符,您会看到不同之处:
[32, 32, 32, 32, 32, 32, 32, 32, 13, 10, 32, ...]
[160, 160, 160, 160, 160, 160, 160, 160, 13, 10, 32, ...]
这160是不能替换的,必须手动去掉,或者拒绝匹配160的再加入再转换:
string = " \r\n Displays the unique ID number assigned to the\r\nAlias Person."
p string.chars.reject { |char| char.ord == 160 }.join
# "\r\n Displays the unique ID number assigned to the\r\nAlias Person."
我有一个字符串
s = " \r\n Displays the unique ID number assigned to the\r\nAlias Person."
我想删除这个开头 space 但它甚至连这些引号也没有删除。
我试过了
s = s.strip!
s = s.gsub!('"','')
代码没有问题。如果您试图从字符串的开头和结尾删除引号,它不会被删除。这就是 ruby 表示字符串的方式。尝试用这样的单引号定义一个字符串:-
2.4.2 :005 > str = 'aaa'
=> "aaa"
您的字符串中的内容是不间断的空格,如果您不在编辑器中使用任何帮助,区别是不可见的:
p " \r\n Displays the unique ID number assigned to the\r\nAlias Person."
p " \r\n Displays the unique ID number assigned to the\r\nAlias Person."
但是如果您映射字符串中的每个字符,您会看到不同之处:
[32, 32, 32, 32, 32, 32, 32, 32, 13, 10, 32, ...]
[160, 160, 160, 160, 160, 160, 160, 160, 13, 10, 32, ...]
这160是不能替换的,必须手动去掉,或者拒绝匹配160的再加入再转换:
string = " \r\n Displays the unique ID number assigned to the\r\nAlias Person."
p string.chars.reject { |char| char.ord == 160 }.join
# "\r\n Displays the unique ID number assigned to the\r\nAlias Person."