From: dblack@... Date: 2006-01-09T23:57:11+09:00 Subject: Re: use of "return" Hi -- On Mon, 9 Jan 2006, SB wrote: > This is a total newbie question, but I'd like to know how "return" is > specifically used in ruby. From my understanding, it can be avoided in a > lot of cases since ruby returns the last value by default. > > However, some of the code in the Rails stuff I'm looking at has "return" and > I was wondering if this "return" is necessary or just the individual > programmer's style (maybe carried over from other languages). > > Sorry, I'm vague but I would like to know how "return" is effectively used > in ruby if at all. > > Here's a code snippet from the SaltedHash Engine > > > def new_security_token(hours = nil) > write_attribute('security_token', AuthenticatedUser.hashed( > self.salted_password + Time.now.to_i.to_s + rand.to_s)) > write_attribute('token_expiry', Time.at(Time.now.to_i + > token_lifetime(hours))) > update_without_callbacks > return self.security_token Programmer's individual style. You could replace that line with: security_token "self" as receiver would be implied, and since it's the last expression evaluated, it would be the return value of the method. > end > > > or this: > > def authenticate(login, pass) > u = find(:first, :conditions => ["login = ? AND verified = 1 AND > deleted = 0", login]) > return nil if u.nil? A return in mid-method needs "return". You could avoid it by rewriting the end of the method like this: if u.nil? nil else other code end But the "return nil if u.nil?" thing both terminates the method and provides a visual cue that u being nil is a terminal condition. So it's partly style, but once you decide to do a mid-method return, you have to use "return". David -- David A. Black dblack@wobblini.net "Ruby for Rails", from Manning Publications, coming April 2006! http://www.manning.com/books/black