0

如果客户的推特句柄是空白的,我希望它默认为另一个推特句柄。对于此示例,假设默认句柄是 @google。

twitter_handle = customer.twitter_name 
#add @ sign if user name doesn't have it
twitter_handle = '@' + customer.twitter_name.gsub.to_s('@', '') unless twitter_handle.blank?

tape_name = name.truncate(27)

"I just bought #{twitter_handle} product}"

我试过了:

twitter_handle = customer.twitter_name || "@google"
twitter_handle = '@' + customer.twitter_name.to_s.gsub('@', '')

我知道错误与这一行有关,因为如果我将其注释掉,它就会起作用:

twitter_handle = '@' + customer.twitter_name.to_s.gsub('@', '')

它切断了整个用户句柄,只返回空白。

tape_name = name.truncate(27)

"I just bought #{twitter_handle} product}"

但我收到此错误:

Sorry, that page does not exist:
 Twitter::Error::NotFound in ProductsController#download 
4

1 回答 1

1

试一试:

编码

twitter_handle = customer.twitter_name ||= '@google'
twitter_handle[/^@/] ? nil : twitter_handle = "@#{twitter_handle}"

没有'@'的测试

1.9.3p194 :001 > twitter_name = 'bjernigan52' #Set without '@' sign
 => "bjernigan52" 
1.9.3p194 :002 > twitter_handle = twitter_name ||= '@google'
 => "bjernigan52" 
1.9.3p194 :003 > twitter_handle[/^@/] ? nil : twitter_handle = "@#{twitter_handle}"
 => "@bjernigan52" 
1.9.3p194 :004 > puts twitter_handle
@bjernigan52
 => nil 

带有“@”的测试

1.9.3p194 :001 > twitter_name = '@bjernigan52'  #Set with '@' sign                                   
 => "@bjernigan52" 
1.9.3p194 :002 > twitter_handle = twitter_name ||= '@google'                       
 => "@bjernigan52" 
1.9.3p194 :003 > twitter_handle[/^@/] ? nil : twitter_handle = "@#{twitter_handle}"
 => nil 
1.9.3p194 :004 > puts twitter_handle                                               
@bjernigan52
 => nil 
于 2012-08-02T04:52:30.350 回答