From: "David A. Black" Date: 2004-09-29T05:37:21+09:00 Subject: Re: DRY ruby idiom Hi -- On Wed, 29 Sep 2004, stevetuckner wrote: > I often use the ||= idiom in ruby for late initialization. But was > recently looking for an idiom that would allow me to overwrite a > variable if the right side is defined without repeating myself. > > I have used the following: > > var = val if val > > but I have to repeat val and that violates DRY. $ ruby -e 'a = b if b' -e:1: undefined local variable or method `b' for main:Object (NameError) > I thought maybe &&= would work, but did not > > var &&= val > > That only works if var and val are non-nil. > > Any ideas out there? I'm not sure it's possible, but it might depend on what state you want to leave things in under what conditions. Even if you do this: var = val if defined?(val) var ends up being nil if val is *not* defined -- so that's indistinguishable from the case where val exists and is nil. If it's OK for var to be nil, then that would be OK, otherwise not. David -- David A. Black dblack@wobblini.net