Interpolating Functions and Expressions Within Strings


(For all intents and purposes, this project is dead, but let us just call it "Deferred Indefinitely". Shall we?)

Problem

You want to expand (or evaluate) the result of a function call or expression within a string.

Solution

You don't need to do anything different in Ruby:

% "1 + 1 = #{1+1} and able was I er#{'able was I e'.reverse} is a palendrome"
"1 + 1 = 2 and able was I ere I saw elba is a palendrome"

Discussion

Unlike perl and many other languages, Ruby's mechanism to embed variables into strings also works with any expression. As a result, you can put nearly anything between "#{}" and it's string representation (by calling #to_s) is interpolated.

Contrast

Perl has some tricky hacks like "${\(some expression)}" where you make a scalar reference to the result of an expression and then immediately dereference it. You can also do the same with a list expression. It is usually more efficient (and easier to read) if you just concatinate expressions together with ".".

Related

TODO: LIST_OF_RELATED_ITEMS

Status: In Progress