From: Jean Helou Date: 2007-01-05T18:27:15+09:00 Subject: Re: How can I do this better? def foo i return @cache[i] ? @cache[i] : some_method_that_takes_long_time(i) end jean 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 > > >