简体   繁体   English

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

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

The app that I'm building allows users to store first and last names of contacts. 我正在构建的应用程序允许用户存储联系人的名字和姓氏。 First names are mandatory, but, last names aren't. 名字是强制性的,但名字不是必需的。 In some cases they exist and in some cases they don't. 在某些情况下,它们存在,在某些情况下则不存在。

I tried using the following logic to replace FNAME and LNAME in the mailer. 我尝试使用以下逻辑替换邮件中的FNAME和LNAME。 I had to use this in the mailer because the logic for sending the group mail gives me no room elsewhere. 我必须在邮件程序中使用它,因为发送组邮件的逻辑在其他地方没有给我任何余地。

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

This throws an undefined method includes?' 这引发undefined method包括吗? with error class NoMethodError`. with错误类NoMethodError`。 Ideally I would like to ignore gsub! 理想情况下,我想忽略gsub! if there is no LNAME or FNAME in the message. 如果消息中没有LNAME或FNAME。

There is a missing dot before the #includes? #includes?之前有一个缺失的点#includes? method call: 方法调用:

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

But you don't need to check the existence of the substring with #includes? 但是您不需要使用#includes?检查子字符串的存在#includes? #gsub! will only replace the content if there is a match, so: 仅在匹配时替换内容,因此:

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

Is enough, if @mailer.message could be nil , then a further check is needed: 足够了,如果@mailer.message可以为nil ,则需要进一步检查:

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

And BTW #gsub! 还有BTW #gsub! will modify the original string, so you probably what you really wanted to write is: 将修改原始字符串,因此您可能真正想写的是:

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