sawa sawa - 4 years ago 206
Ruby Question

Evaluating a frozen string

My vague understanding is that, with Ruby 2.2's

frozen
method on string or Ruby 2.3's
frozen-string-literal: true
pragma, a relevant frozen string literal is evaluated only once throughout program execution if and only if the string does not have interpolation. The following seems to illustrate this:

Not interpolated

#frozen-string-literal: true
5.times{p "".object_id}


Outputs (same object IDs):

70108065381260
70108065381260
70108065381260
70108065381260
70108065381260


Interpolated

#frozen-string-literal: true
5.times{p "#{}".object_id}


Outputs (different object IDs):

70108066220720
70108066220600
70108066220420
70108066220300
70108066220180



  1. What is this property (i.e., being evaluated only once) called? It should be distinct from immutability.

  2. Is my understanding of the condition when strings come to have such property correct? Where is the official documentation mentioning this?

  3. Is there a way to make an interpolated string be evaluated only once?


Answer Source
  1. Interning. The strings are said to be internalized.
  2. Not completely. It is more like if the interpreter can decide what the value of the string would be before evaluating it (will look a little more on how this happens). For example, consider:

    5.times { puts "#{'foo'}".object_id }
    

    The id is the same even though there is interpolation involved.

  3. Going to guess not.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download