Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!us.feeder.erje.net!goblin1!goblin.stu.neva.ru!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.ruby Subject: Re: Proposal for easier syntax for define-unless-already-defined pattern Date: Wed, 30 Jul 2014 19:45:24 +0200 Lines: 31 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net JeJDQjIiJkPQmezVZVxgrAkg7xtm+/RmuPwcPEofJwUL2seGc= Cancel-Lock: sha1:O9wR1aVon1jQwDYqyFghlY/OO2Q= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.0 In-Reply-To: Xref: csiph.com comp.lang.ruby:7007 On 29.07.2014 18:40, Eugene Gilburg wrote: > Below pattern is very popular in Ruby, but does not work if the > method returns `nil` or `false`: > > @obj ||= some_expensive_method() > > For more consistent and efficient use of this pattern, you'd have to > write: > > if defined?(@obj) @obj else @obj = some_expensive_method() end > > Because above syntax is clunky, people tend not to use it, with the > less efficient ||= being far more common. Where is this less efficient? I don't think it is. > So what do you think of `?=` syntax below, to exactly replicate the > above code block? It should check not value of variable but only > whether the variable itself is defined: > > @obj ?= some_expensive_method() Operator ||= works remarkably good in practice and for the rare cases where #some_expensive_method returns nil or false the user can use the test with #defined? explicitly. Not sure whether that small benefit warrants a language change. Kind regards robert