Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Symbols are like strings but they are immutable - they can't be modified.</p> <p>They are only put into memory once, making them very efficient to use for things like keys in hashes but they stay in memory until the program exits. This makes them a memory hog if you misuse them.</p> <p>If you dynamically create lots of symbols, you are allocating a lot of memory that can't be freed until your program ends. You should only dynamically create symbols (using <code>string.to_sym</code>) if you know you will:</p> <ol> <li>need to repeatedly access the symbol</li> <li>not need to modify them</li> </ol> <p>As I said earlier, they are useful for things like hashes - where you care more about the <strong>identity</strong> of the variable than its value. Symbols, when correctly used, are a readable and efficient way to pass around identity.</p> <p>I will explain what I mean about the immutability of symbols RE your comment.</p> <p>Strings are like arrays; they can be modified in place:</p> <pre><code>12:17:44 ~$ irb irb(main):001:0&gt; string = "Hello World!" =&gt; "Hello World!" irb(main):002:0&gt; string[5] = 'z' =&gt; "z" irb(main):003:0&gt; string =&gt; "HellozWorld!" irb(main):004:0&gt; </code></pre> <p>Symbols are more like numbers; they can't be edited in place:</p> <pre><code>irb(main):011:0&gt; symbol = :Hello_World =&gt; :Hello_World irb(main):012:0&gt; symbol[5] = 'z' NoMethodError: undefined method `[]=' for :Hello_World:Symbol from (irb):12 from :0 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload