views:

80

answers:

4

The following Ruby code

def a(b,c) b+c end 

is the same as follows with Python

def a(b,c): return b+c

It looks like that ruby has the special stack that stores the final evaluation result and returns the value when a function is called.

  • If so, what's the name of the stack, and how can I get that stack?
  • If not, how does the Ruby code work without returning something?
+2  A: 

I don't think it's a stack. The final evaluation of the function is simply the return value, plain and simple. Just your everyday Ruby syntactic sugar.

Matchu
+5  A: 

It's not that magic, Ruby just returns the value returned by the operation that does at the end.

It's synctactic sugar that it's implemented just at parsing level: a statement that calculates something implicitly returns itself without any keyword..

to clarify it a little bit you can imagine both abstract syntax trees of the two snippets: they won't be different.

Jack
+1  A: 

I don't see any reason why a stack should be required to return a result. A simple pointer to a memory location would be sufficient. I'd guess that would usually be returned in a register, such as EAX.

You get the return value of a function by assigning the function's value to a variable (or doing something else with it). That's the way it was intended to be used, and the only way that works.

Not returning anything is really easy: The called function doesn't put anything into the return location (whatever it may be) and the caller ignores it.

Carl Smotricz
+1  A: 

Actually, return is special here, not the standard behavior. Consider:

def foo(ary)
  ary.each do |e|
    return true if e == 2
  end
end

This code actually has more then one stack frame (at least the on for #foo, the one for Array#each and the one for the anonymous function passed to #each). What return does: it does a jump to the stack frame of the outermost lexical scope it is called in (the end of foo) and returns the given value. If you play a lot with anonymous functions, you will find that return is no allowed in all context, while just returning the last computed value is.

So I would recommend never to use return if you don't need it for precisely that reason: breaking and returning from a running iteration.

Skade