Sergey Metlov
Sergey Metlov

Reputation: 26301

Pattern string formatting

It is possible to format string like this:

text = 'text'
formatted = "Text: #{text}"

What about the following?

pattern = "Text: #{text}"
text = 'text'
formatted = ???

Upvotes: 1

Views: 1979

Answers (2)

Leonid Beschastny
Leonid Beschastny

Reputation: 51480

Pattern formatting in coffeescript is a part of coffeescript->javascript compiler.

So,

pattern = "Text: #{text}"

instantly compiles into

pattern = "Text: " + text;

It's why

pattern = "Text: #{text}"
text = 'text'

will throw an error "text is not defined".

But you can wrap it in a function like this:

pattern = (text) -> "Text: #{text}"
text = 'text'
formatted = pattern text

or like this:

pattern = ({text1, text2, text3}) -> "Text: #{text1}, #{text2} and #{text3}"
text1 = 'text'
text2 = 'awesome text'
text3 = 'another text'
formatted = pattern {text1, text2, text3}

Upvotes: 7

phenomnomnominal
phenomnomnominal

Reputation: 5515

No, the string interpolation syntax doesn't work like that. This is possibly a better way to achieve the exact same thing though:

pattern = 'Text: #{text}'
text = 'text'
formatted = pattern.replace /#{text}/, text

Upvotes: -1

Related Questions