From: gaurav bagga Date: 2007-01-05T18:26:22+09:00 Subject: Re: How can I do this better? ------=_Part_884_30232773.1167989179982 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline hi, def foo i @cache[i]||=some_method_that_takes_long_time(i) end if @cache[i] is not nil it will return same value else the other regards gaurav On 1/5/07, Sam Kong wrote: > > Hi, > > I find myself to use the following idiom frequently. > > def foo i > return @cache[i] if @cache[i] > @cache[i] = some_method_that_takes_long_time(i) > end > > I like the post-modifying if statement. > But I feel uncomfortable with calling @cache[i] twice. > > I wish this worked. > return v if v = @cache[i] #=> undefined local variable or method `v' > > This works but it's long. > if v = @cache[i] > return v > end > > Maybe this is a compromise. > if v = @cache[i] then return v end > > I want "return statement" to stand out. > Post-modification looks better for that. > So I call @cache[i] twice. > > How do you do it? > > Sam > > > ------=_Part_884_30232773.1167989179982--