简体   繁体   English

单引号字符串字符串插值

[英]Single quote string string interpolation

I am trying to set an email address within ActionMailer with Rails. 我正在尝试使用Rails在ActionMailer中设置电子邮件地址。 Before it was hard coded, but we want to make them ENV variables now so we don't need to amend code each time an email changes. 在硬编码之前,我们现在想让它们成为ENV变量,这样我们就不需要在每次电子邮件更改时修改代码。

Here is how it's currently defined: 以下是它目前的定义:

from = '"Name of Person" <email@email.com>'

I've tried setting the email as an environment variable using ENV['EMAIL'] but I'm having no luck even with #{ENV['EMAIL'} . 我已尝试使用ENV['EMAIL']将电子邮件设置为环境变量,但即使使用#{ENV['EMAIL'}我也没有运气。

Can anyone point me in the right direction? 谁能指出我正确的方向?

You cannot use string interpolation with single-quoted strings in Ruby. 你不能在Ruby中使用单引号字符串的字符串插值。

But double-quoted strings can! 但双引号字符串可以!

from = "'Name of Person' <#{ENV['EMAIL']}>"

But if you want to keep your double-quotes wrapping the Name of Person , you can escape them with a backslash \\ : 但是如果你想保留你的双引号包装Name of Person ,你可以用反斜杠\\来转义它们:

from = "\"Name of Person\" <#{ENV['EMAIL']}>"

Or use string concatenation: 或者使用字符串连接:

from = '"Name of Person" <' + ENV['EMAIL'] + '>'
# but I find it ugly

If you want to embed double quotes in an interpolated string you can use % notation delimiters (which Ruby stole from Perl), eg 如果你想在插值字符串中嵌入双引号,你可以使用%表示法分隔符(Ruby从Perl中窃取),例如

from = %|"Name of Person", <#{ENV['EMAIL']}>|

or 要么

from = %("Name of Person", <#{ENV['EMAIL']}>)

Just pick a delimiter after the % that isn't already in your string. 只需在字符串中尚未包含的%之后选择一个分隔符。

You can also use format . 您也可以使用format I have not seen it used as commonly in Ruby as in other languages (eg C, Python), but it works just as well: 我没有看到它像在其他语言(例如C,Python)中一样在Ruby中使用,但它也可以正常工作:

from = format('"Name of Person", <%s>', ENV["EMAIL"])

Alternative syntax using the % operator: 使用%运算符的替代语法:

from = '"Name of Person", <%s>' % ENV["EMAIL"]

Here is the documentation for format (aka sprintf ): 这是format (aka sprintf )的文档:

http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-format http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-format

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

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