I have a question regarding the ||= statement in ruby and this is of particular interest to me as I’m using it to write to memcache. What I’m wondering is, does ||= check the receiver first to see if it’s set before calling that setter, or is it literally an alias to x = x || y
This wouldn’t really matter in the case of a normal variable but using something like:
CACHE[:some_key] ||= "Some String"
could possibly do a memcache write which is more expensive than a simple variable set. I couldn’t find anything about ||= in the ruby api oddly enough so I haven’t been able to answer this myself.
Of course I know that:
CACHE[:some_key] = "Some String" if CACHE[:some_key].nil?
would achieve this, I’m just looking for the most terse syntax.
This is extremely easy to test:
Now simply try the
||=syntax:So we can conclude that no assignment takes place if the cache key already exists.
The following extract from the Rubyspec shows that this is by design and should not be dependent on the Ruby implementation:
In the same file, there is a similar spec for
[]and[]=that mandates identical behaviour.Although the Rubyspec is still a work in progress, it has become clear that the major Ruby implementation projects intend to comply with it.