Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is extremely easy to test:</p> <pre><code>class MyCache def initialize @hash = {} end def []=(key, value) puts "Cache key '#{key}' written" @hash[key] = value end def [](key) puts "Cache key '#{key}' read" @hash[key] end end </code></pre> <p>Now simply try the <code>||=</code> syntax:</p> <pre><code>cache = MyCache.new cache["my key"] ||= "my value" # cache value was nil (unset) # Cache key 'my key' read # Cache key 'my key' written cache["my key"] ||= "my value" # cache value is already set # Cache key 'my key' read </code></pre> <p>So we can conclude that no assignment takes place if the cache key already exists.</p> <p>The following extract from the Rubyspec <a href="http://github.com/rubyspec/rubyspec/blob/master/language/variables_spec.rb" rel="noreferrer">shows</a> that this is <strong>by design</strong> and should not be dependent on the Ruby implementation:</p> <pre><code>describe "Conditional operator assignment 'obj.meth op= expr'" do # ... it "may not assign at all, depending on the truthiness of lhs" do m = mock("object") m.should_receive(:foo).and_return(:truthy) m.should_not_receive(:foo=) m.foo ||= 42 m.should_receive(:bar).and_return(false) m.should_not_receive(:bar=) m.bar &amp;&amp;= 42 end # ... end </code></pre> <p>In the same file, there is a similar spec for <code>[]</code> and <code>[]=</code> that mandates identical behaviour.</p> <p>Although the Rubyspec is still a work in progress, it has become clear that the major Ruby implementation projects intend to comply with it.</p>
 

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