From: "David A. Black" Date: 2004-02-15T00:53:53+09:00 Subject: Re: Simple litle style question Hi -- On Sun, 15 Feb 2004, Kirk Haines wrote: > This is just a simple little stylistic query that I became curious about > after one of Ara Howard's questions the other day. > > In general, do people prefer: > > def simpleExample(t) I prefer "simple_example" :-) > x = block_meth do > r = nil You don't actually need that in this case; an if clause does not start a new scope. > if t == 'forty-two' > r = 42 > else > r = 0 > end > r > end > > x > end > > > or: > > def simpleExample(t) > x = block_meth do > if t == 'forty-two' > r = 42 > else > r = 0 > end > end > end Do you need "x =" or "r =" there at all? I think the all-out implementation of this approach would just be: def simple_example(t) block_meth do if t == 'forty-two' 42 else 0 end end end And, just for fun, there's also: def simple_example(t) block_meth { if t == 'forty-two' then 42 else 0 end } end def simple_example(t) block_meth { t == 'forty-two' ? 42 : 0 } end and even def simple_example(t) block_meth do case t when 'forty-two' then 42 else 0 end end end (I won't bother with the "t == 'forty-two' && 42 || 0" one :-) > both assuming this method is available: > > def block_meth > yield > end > > > i.e. do you explicity declare a return variable and put that variable > right before the 'end' or do you rely on your audience being smart enough > to perceive what the return value is going to be? > > On a really short piece of code like this, I appreciate the elegant > simplicity of not being explicit, though my person trend is to be explicit > anyway. On a longer piece of code, though, I can certainly see where it > might not be as clear to a reader of the code just what is being returned, > especially from a casual scan, if it is not done explicitly. > > Is this clarity helpful, or is it a minor enough thing that the ugliness > that it imparts to the code isn't worth it? What do you all think? Personally I tend to like to avoid temporary variables and accumulators in that situation, if possible. But I don't think it's too ugly, usually, just a bit longer. [Note: all code untested] David -- David A. Black dblack@wobblini.net