我有一个变量address
,现在是一个包含一些不必要信息的长字符串,例如:"Aboriginal Relations 11th Floor Commerce Place 10155 102 Street Edmonton AB T5J 4G8 Phone 780 427-9658 Fax 780 644-4939 Email gerry.kushlyk@gov.ab.ca"
Aboriginal Relations
位于名为title
的变量中,我正在尝试调用address.gsub!(title,'')
,但它会返回原始字符串。
我也尝试了address.gsub!(/#{title}/,'')
和address.gsub!("#{title}",'')
,但这些也无效。有什么想法吗?
很抱歉,当我输入堆栈溢出时出现错字,继承代码和输出,复制并粘贴:
(这是一个循环,所以会有多个输出)
p title
address.gsub!(title,'')
p address
输出
"Aboriginal Relations "
"Aboriginal Relations 11th Floor Commerce Place 10155 102 Street Edmonton AB T5J 4G8 Phone 780 427-9658 Fax 780 644-4939 Email gerry.kushlyk@gov.ab.ca"
"Aboriginal Tourism Advisory Council "
"Aboriginal Tourism Advisory Council 5th Floor Terrace Building 9515 107 Street Edmonton AB T5K 2C3 Phone 780 427-9687 Fax 780 422-7235 Email foip.fintprccs@gov.ab.ca"
"Acadia Foundation "
"Acadia Foundation PO Box 96 Oyen AB T0J 2J0 Phone 403 664-3384 Fax 403 664-3316 Email acadiafoundation@telus.net"
"Access Advisory Council "
"Access Advisory Council 12th Floor Centre West Building 10035 108 Street Edmonton AB T5J 3E1 Phone 780 427-2805 Fax 780 422-3204 Email barb.joyner@gov.ab.ca"
"ACCM Benevolent Association "
"ACCM Benevolent Association Suite 100 9403 95 Avenue Edmonton AB T6C 4M7 Phone 780 468-4648 Fax 780 468-4648 Email accmmanor@shaw.ca"
"Acme Municipal Library "
"Acme Municipal Library PO Box 326 Acme AB T0M 0A0 Phone 403 546-3845 Fax 403 546-2248 Email aamlibrary@marigold.ab.ca"
同样,如果我尝试address.match(/#{title}/)
,我会得到零。
答案 0 :(得分:1)
我假设您使用的是ruby 1.9或更高版本。 尾部空格可能是一个不间断的空间:
p "Relations\u00a0" # looks like a trailing space, but strip won't remove it
摆脱它:
"Relations\u00a0".gsub!(/^\u00a0|\u00a0$/, '') # => "Relations"
所有unicode空格的更通用的解决方案:
"Relations\u00a0".gsub!(/^[[:space:]]|[[:space:]]$/, '') # => "Relations"
要查看您案件中的角色:
title[-1].ord # => 160 (example only)
'%x' % title[-1].ord # => "a0" (hex equivalent; example only)
答案 1 :(得分:0)
title = title[0..-2]
似乎解决了这个问题。出于某种原因strip
和chomp
不起作用。