Does Ruby have a dedicated store for returning a value?

The following Ruby code

def a(b,c) b+c end 

      

is the same as Python

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

      

It looks like ruby ​​has special storage (stack or whatever) that stores the final score and returns a value when the function is called.

  • If so, what is the name of the stack and how can I get this stack?
  • If not, how does Ruby code work without returning something?
+2


a source to share


4 answers


This is not magic, Ruby simply returns the return value of the operation that is executed at the end.

This is syntactic sugar that he only implemented at the parsing level: an operator that evaluates something implicitly returns itself without any keyword.



To clarify this a bit, you can think of the two fragments as abstract syntax trees: they will not differ.

+5


a source


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



+2


a source


I see no reason why a stack should be required to return a result. A simple pointer to a memory location is enough. I would suggest that it usually returns to a register, for example EAX

.

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

Not returning anything is really easy: the called function does not place anything in the returned location (whatever it is), and the caller is oblivious to it.

+1


a source


In fact, returning is special, not standard behavior. Consider:

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

      

This code actually has more than one stack frame (at least for #foo, for Array # and for the anonymous function passed to #each). What it returns: It jumps to the stack frame from the lexical scope itself it calls to (end of foo) and returns the given value. If you play around with anonymous functions a lot, you will find that return is not allowed in all contexts, but only the return of the last computed value.

Therefore, I would recommend never to use return unless you need it for this very reason: break and return from the current iteration.

+1


a source







All Articles