From: Paul Brannan Date: 2002-03-19T22:56:06+09:00 Subject: Re: style choice On Tue, Mar 19, 2002 at 10:19:42PM +0900, Ron Jeffries wrote: > A style question for the community ... which of the following do you prefer, and > why? Or, if you prefer some third version, what is it and why? > > def degree > return @degree if @degree > 0 > @scopes.each { | field | @degree += field.length } > @degree > end > > def degree > @scopes.each { | field | @degree += field.length } if @degree == 0 > @degree > end I prefer the top one over the bottom one, because it doesn't try to cram as much as possible into one line. Many C programmers like to do this, but I don't think it's a good idea in either language (C or Ruby). One problem I see with the first solution is that the statement: return @degree if @degree > 0 does not emphasize the condition "if @degree > 0", but the more I write Ruby code, the less of an issue this is. However, since many of my co-workers have a hard time reading code written this way, I tend to write like the following instead: if @degree > 0 then return @degree end even if it is a single statement inside the if..end. This also means less editing when I want to add a second statement. The other issue is that making: @degree be the last statement doesn't emphasize that you intend to return that value. Since it is faster than using: return @degree I tend to write instead: @degree #return though I think Ruby should optimize the case where return is the last statement in the method for me. Paul