In SO question 2068165 one answer raised the idea of using something like this:
params[:task][:completed_at] &&= Time.parse(params[:task][:completed_at])
as a DRYer way of saying
params[:task][:completed_at] = Time.parse(params[:task][:completed_at]) if params[:task][:completed_at]
where the params Hash would be coming from a (Rails/ActionView) form.
It’s a kind of corollary to the well-known ||= idiom, setting the value if the LHS is not nil/false.
Is using &&= like this actually a recognised Ruby idiom that I’ve somehow missed or have I just forgotten a more commonly-used idiom? It is getting rather late…
It ought to be. If nothing else,
params[:task]is only evaluated once when using the&&=form.To clarify:
calls
[](:task)onparamstwice,[](:completed_at)and[]=(:completed_at)once each onparams[:task].calls
[](:task)onparamsonce, and its value is stashed away for both the[](:completed_at)and[]=(:completed_at)calls.Actual example describing what I’m trying to illustrate (based on Marc-Andre’s example code; much thanks):
Note that using the “expanded” form causes “get” to be printed out twice, but using the compact form causes it to only be printed once.