From: dblack@... Date: 2007-02-19T23:20:24+09:00 Subject: Re: return statement Hi -- On Mon, 19 Feb 2007, Derek Teixeira wrote: >> Return means "we are done". >> >> Sometimes when you write a method (I don't know the jargon used in >> that book, it may be function, or subroutine, or procedure, ...) you >> know somewhere in the middle that _if the code reached that point_ we >> do not need to do anything else. For instance, see this method that >> says where the given number is positive: >> >> def is_positive?(n) >> if n > 0 >> return true >> end >> return false >> end >> >> That method can be written in different ways, but to depict the >> meaning of return: if n is greater than 0, you already know the >> answer, so in that point you indicate there's no need to execute more >> code, you're ready to give the answer: true. If the execution reaches >> that point, the following executable line "return false" will be >> ignored altogether, execution is halted. >> >> Return in addition accepts a value to be returned (true/false in the >> example), which is considered to be the _result_ of that method call >> in such case. > > So you are saying that it basically saves the confusion of elsif's and > it just makes more sense.. in your example you could have easily written > > def is_positive?(n) > if n > 0 > answer= true > elsif > n<0 > answer= false > end > > Right? but that just looks sloppy and could really get confusing if i > had more lines of code.. am i getting it right? Well, in that particular case, I would just do: def is_positive?(n) n > 0 end You definitely don't need the temporary variable (answer), and in fact you don't need to code the true/false return values because > will already give you one or the other. David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)