简体   繁体   中英

Single quote string string interpolation

I am trying to set an email address within ActionMailer with Rails. 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.

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'} .

Can anyone point me in the right direction?

You cannot use string interpolation with single-quoted strings in 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 \\ :

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

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 . I have not seen it used as commonly in Ruby as in other languages (eg C, Python), but it works just as well:

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 ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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