Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of output

Tags:

ruby

The code below:

def a
  print "Function 'a' called\n"
  99
end

print "a=", a, "\n"

produces:

Function 'a' called
a=99

Why does function 'a' called show first? I expected a= to be shown first.

like image 278
Dreams Avatar asked Jul 10 '13 09:07

Dreams


2 Answers

Before arguments are passed to a method, they are evaluated (so that you have values to pass). Evaluation of a call to function a has a side effect of printing "function 'a' called. That's why it is printed first.

like image 93
Sergio Tulentsev Avatar answered Oct 05 '22 22:10

Sergio Tulentsev


First, you define the method a; nothing is printed yet.

Then, when you get to the last line, the arguments to print are first evaluated before that statement prints anything. The first and last arguments are string literals. The middle argument is a call to the method a, which prints "Function 'a' called\n" before returning 99.

Then, the print statement that started all this is finally ready to print now that each of its arguments has been evaluated.

like image 38
Darshan Rivka Whittle Avatar answered Oct 06 '22 00:10

Darshan Rivka Whittle