2 ms·
That is not the same, because Object#present? is a test for nonblankness, not definedness. So, for example, the empty string "" returns nil for #presence, which
by inopinatus 2y ago
That is not the same, because Object#present? is a test for nonblankness, not definedness. So, for example, the empty string "" returns nil for #presence, which is exactly what we don't want when caching the result of a potentially expensive templating operation, external service query etc.
The proper equivalent uses the defined? keyword, as in
(defined? @result) ? @result : @result = ""
which will produce @result with conditional assignment over definition. Note that defined? is a keyword, not an operator.
There is no shorthand for this expression. There's less motivation because instance variables are better accessed symbolically. If you're not the accessor code then it's none of your business, and if you are a memoizing accessor then your specialist action doesn't really warrant an operator simply for golf. This isn't autovivification but Perl has that as an adjacent idea already, and all this adds up to the //= operator making a lot more idiomatic sense and holding more purpose in Perl than it does in Ruby.