繁体   English   中英

仅当字符串包含在文本中时才使用gsub

[英]Using gsub only when the string is included in the text

我正在构建的应用程序允许用户存储联系人的名字和姓氏。 名字是强制性的,但名字不是必需的。 在某些情况下,它们存在,在某些情况下则不存在。

我尝试使用以下逻辑替换邮件中的FNAME和LNAME。 我必须在邮件程序中使用它,因为发送组邮件的逻辑在其他地方没有给我任何余地。

message = @mailer.message.gsub! 'FNAME', contact.first_name if @mailer.message includes? ('FNAME')
@body = message.gsub! 'LNAME', contact.last_name || '' if message includes?('LNAME')

这引发undefined method包括吗? with错误类NoMethodError`。 理想情况下,我想忽略gsub! 如果消息中没有LNAME或FNAME。

#includes?之前有一个缺失的点#includes? 方法调用:

message = @mailer.message.gsub! 'FNAME', contact.first_name if @mailer.message.includes?('FNAME')

但是您不需要使用#includes?检查子字符串的存在#includes? #gsub! 仅在匹配时替换内容,因此:

message = @mailer.message.gsub!('FNAME', contact.first_name)

足够了,如果@mailer.message可以为nil ,则需要进一步检查:

message = @mailer.message.gsub!('FNAME', contact.first_name) if @mailer.message.present?

还有BTW #gsub! 将修改原始字符串,因此您可能真正想写的是:

if @mailer.message.present?
  @mailer.message.gsub!('FNAME', contact.first_name)
  @mailer.message.gsub!('LNAME', contact.last_name)
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM