On Fri, Jan 05, 2007 at 06:05:32PM +0900, Sam K. 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
[…]
} How do you do it?
return v if v = @cache[i] #=> undefined local variable or method `v’
Hi Sam
that is too bad I did not know about that, good you showed us.
Maybe you like the following code(1):
v = @cache[i] and return v
but I agree that
return v if v = @cache[i]
would be nicer
(1) some people wondered recently why “or” and “and” have such low a
precedence, I guess this example is a reason behind this.
HTH
Robert
I want “return statement” to stand out.
Sorry I cannot do that
Post-modification looks better for that.
So I call @cache[i] twice.
How do you do it?
Sam
Robert
–
“The real romance is out ahead and yet to come. The computer revolution
hasn’t started yet. Don’t be misled by the enormous flow of money into
bad
defacto standards for unsophisticated buyers using poor adaptations of
incomplete ideas.”
(1) some people wondered recently why “or” and “and” have such low a
precedence, I guess this example is a reason behind this.
Probably because ruby provides “||” and “&&” also for higher
precedence.
I think so too, but just one worry, did you read me here?
Tthis was only a side remark but what I meant is
v = … and return v # does what you want
v = … && return v # is not even correct syntax
Cheers
R.
Thanks.
Sam
–
“The real romance is out ahead and yet to come. The computer revolution
hasn’t started yet. Don’t be misled by the enormous flow of money into
bad
defacto standards for unsophisticated buyers using poor adaptations of
incomplete ideas.”
Of course, I read you.^^
That’s a good suggestion. @cache[i] ||= some_method(i) kills all others, though.
Now that is funny, how stubborn I was, of course that is what you
wanted,
but I really had the feeling that you were angry
about
return v if v = x()
which one might be angry about and I think that was a good point.
I should have realized that the method around the “return … if” had
not
context purpose, the method was what you were worried about.
Of course ||= is what you are looking for.
Cheers
Robert
Thanks.
Sam
–
“The real romance is out ahead and yet to come. The computer revolution
hasn’t started yet. Don’t be misled by the enormous flow of money into
bad
defacto standards for unsophisticated buyers using poor adaptations of
incomplete ideas.”