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...
Reasonable use means the minimum use to which a property owner is entitled under the applicable state and federal constitutional provisions, including takings and substantive due process. Reasonable use shall be liberally construed to protect the constitutional rights of the property owner.
INTRODUCTION. The Reasonable and Beneficial Use Doctrine (Reasonable Use Doctrine) is the cornerstone of California's complex water rights laws. All water use must be reasonable and beneficial regardless of the type of underlying water right. No one has an enforceable property interest in the unreasonable use of water.
Related Definitions Right to Use means a right to disclose, copy, duplicate, reproduce, modify and otherwise use.
It ought to be. If nothing else, params[:task]
is only evaluated once when using the &&=
form.
To clarify:
params[:task][:completed_at] = params[:task][:completed_at] && ...
calls [](:task)
on params
twice, [](:completed_at)
and []=(:completed_at)
once each on params[:task]
.
params[:task][:completed_at] &&= ...
calls [](:task)
on params
once, 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):
class X
def get
puts "get"
@hash ||= {}
end
end
irb(main):008:0> x = X.new
=> #<X:0x7f43c496b130>
irb(main):009:0> x.get
get
=> {}
irb(main):010:0> x.get[:foo] = 'foo'
get
=> "foo"
irb(main):011:0> x.get[:foo]
get
=> "foo"
irb(main):012:0> x.get[:foo] &&= 'bar'
get
=> "bar"
irb(main):013:0> x.get[:foo] = x.get[:foo] && 'bar'
get
get
=> "bar"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With