3 ms·
> I don't think Ruby has this natively, but Rails adds it with Object#presence. > https://api.rubyonrails.org/classes/Object.html#method-i-presence https://api
by JadeNB 2y ago
> I don't think Ruby has this natively, but Rails adds it with Object#presence.
> https://api.rubyonrails.org/classes/Object.html#method-i-presence https://api.rubyonrails.org/classes/Object.html#method-i-pre...
It's not immediately obvious to me how one could use that to write a Ruby analogue of `a //= b`. If I understand correctly, it would still need to be the relatively verbose `a = a.present? ? a : b`. (I think even `a = a.presence || b` wouldn't work in case `a` was defined but nil, which is exactly the edge case the defined-or operator is meant to handle.)
- the_sleaze_ 2y agoI use this to memoize instance vars from time to time, whenever nil could be considered valid return x if defined? x x = ingest_stock_market `defined?` won't evaluate the parameter either which is nice whereas things like blank? present? and presence do
- JadeNB 2y ago> return x if defined? x It's a natural pattern, and translates with obvious changes to Perl, but still `x = defined? x ? x : y` is longer than `x //= y`, so all I was meaning to say in my original comment was that I was surprised that Ruby didn't borrow the latter from Perl.