RileyE
RileyE

Reputation: 11074

Perform operations within string format

I am sure that this has been asked, but I can't find it through my rudimentary searches.

Is it discouraged to perform operations within string initializations?

  > increment = 4
 => 4 
  > "Incremented from #{increment} to #{increment += 1}"
 => "Incremented from 4 to 5"

Upvotes: 0

Views: 48

Answers (2)

sawa
sawa

Reputation: 168071

In your particular case, it might be okay, but the problem is that the position where the operation on the variable should happen must be the last instance of the same variable in the string, and you cannot always be sure about that. For example, suppose (for some stylistic reason), you want to write

"Incremented to #{...} from #{...}"

Then, all of a sudden, you cannot do what you did. So doing operation during interpolation is highly dependent on the particular phrasing in the string, and that decreases maintainability of the code.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160170

I sure wouldn't, because that's not where you look for things-that-change-things when reading code.

It obfuscates intent, it obscures meaning.


Compare:

url = "#{BASE_URL}/#{++request_sequence}"

with:

request_sequence += 1
url = "#{BASE_URL}/#{request_sequence}"

If you're looking to see where the sequence number is coming from, which is more obvious?

I can almost live with the first version, but I'd be likely to opt for the latter. I might also do this instead:

url = build_url(++request_sequence)

Upvotes: 3

Related Questions