Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 protected]>'

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?

like image 386
DMH Avatar asked Apr 23 '15 15:04

DMH


People also ask

How do you handle a single quote in a string?

So, to allow values within single quotes (and some other special characters) to be used within a string, you need to “escape” them. Escaping a character is where you say to the database, “Hey, this character here is part of my string, don't treat it as a special character like you normally would”.

What is interpolation string?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

Can we write string in single quotes?

Using Single-Quoted strings: While using single-quoted strings for defining string literals, we only need to escape the single quote inside the string. While there is no need to escape double-quote and can be written exactly.

How do you escape quotation marks in a string?

' You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string.


2 Answers

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
like image 103
MrYoshiji Avatar answered Sep 20 '22 10:09

MrYoshiji


If you want to embed double quotes in an interpolated string you can use % notation delimiters (which Ruby stole from Perl), e.g.

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.

like image 22
Mori Avatar answered Sep 20 '22 10:09

Mori