From: Jacob Fugal Date: 2006-05-10T00:40:37+09:00 Subject: Re: code snippet: can it be done better/shorter? On 5/9/06, Krekna Mektek wrote: > A bit late, but I was reading this post again, but your code is > actually not the same, if I understood you right. > > because from is assigned "Unknown" if it's an empty string. > And from || "Unknown" results in true if from is defined, so the value > "Unknown" is not assigned to it. Right? The value "Unknown" will not be assigned to from, but it doesn't need to be. An expression of the form 'a || b' is equivalent to this: a ? a : b or more verbosely: if a then a else b end So, if from evaluates true in a boolean context -- which it will unless a is nil or false -- the value of a is used as the value of the expression, not the value 'true'. And if a evaluates false in a boolean context, then the value of b is used. So the expression 'from || "Unknown"' will return either the value of from, or the value "Unknown" if from has from has a value of nil or false. And since from has a value of nil iff REG did not match, the value "Unknown" will be used iff REG does not match. When REG does match, the value of the capture from the regular expression will be used (even if that value is "", since an empty string is a true value in Ruby). Jacob Fugal