繁体   English   中英

单引号字符串字符串插值

[英]Single quote string string interpolation

我正在尝试使用Rails在ActionMailer中设置电子邮件地址。 在硬编码之前,我们现在想让它们成为ENV变量,这样我们就不需要在每次电子邮件更改时修改代码。

以下是它目前的定义:

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

我已尝试使用ENV['EMAIL']将电子邮件设置为环境变量,但即使使用#{ENV['EMAIL'}我也没有运气。

谁能指出我正确的方向?

你不能在Ruby中使用单引号字符串的字符串插值。

但双引号字符串可以!

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

但是如果你想保留你的双引号包装Name of Person ,你可以用反斜杠\\来转义它们:

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

或者使用字符串连接:

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

如果你想在插值字符串中嵌入双引号,你可以使用%表示法分隔符(Ruby从Perl中窃取),例如

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

要么

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

只需在字符串中尚未包含的%之后选择一个分隔符。

您也可以使用format 我没有看到它像在其他语言(例如C,Python)中一样在Ruby中使用,但它也可以正常工作:

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

使用%运算符的替代语法:

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

这是format (aka sprintf )的文档:

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