dblack / wobblini.net wrote:
> 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
> 

"return" is required if you want to return multiple values like this:

   def foo
     return "a", "b", "c"
   end

Though you can also do this

   def foo
     ["a", "b", "c"]
   end

Personally, I always use "return" if the name of the variable/method is 
short.

   # Short names
   return result
   return value

   # Long name, no "return" keyword
   Foo::Bar.bur(1, 2, 3)

   # Method call with arguments, no "return" keyword
   foobar(1, 2, 3)
   barfoo 1, 2, 3


Cheers,
Daniel