Just Another Victim of the Ambient Morality
3/29/2006 5:39:00 AM
"Dirk Traulsen" <dirk.traulsen@lypso.de> wrote in message
news:442A2F49.10564.F61BC9B@dirk.traulsen.lypso.de...
> Hi list!
>
> I had a strange effect, when I combined print with several strings
> and a method.
> Please look at this example:
>
> ##############
> def method1
> print "string_2_method", " - "
> return "return_string_method - "
> end
>
> print "\n"
> print "string_1", " - ", method1, "string_3\n"
> ##############
>
> Surprisingly it results in:
> string_2_method - string_1 - return_string_method - string_3
>
> But I expected it to result in:
> string_1 - string_2_method - return_string_method - string_3
>
> Even if any method would be executed first, independant of the
> position in the line, then shouldn't it be the following:
> string_2_method - return_string_method - string_1 - string_3
>
> Can somebody please explain this strange order of execution to me?
Interestingly enough, this doesn't really have anything to do with Ruby,
in particular...
In your example, "method1" is a method call that executes and returns a
value. You are calling it as a parameter to another method call, the one to
"print." Just in case it makes it more clear to you, I will add the
optional brackets like how you would have to in some other languages...
print("\n")
print( "string_1", "-", method1(), "string3\n");
So, you're calling "print" and passing it four parameters. But, with
the third parameter, you're passing in the return value of "method1."
Therefore, you need to call it and, as such, you will be calling it before
you call "print." But "method1" has a side effect. It calls:
print( "string_2_method", "-") # brackets added for possible clarity...
So, because "method1" is called first, the string printed from within
that method gets printed first, as its side effect. Then the return value
of that method gets returned to the caller, as a parameter to the method
call "print." So then "print" gets called with its four parameters and they
are printed, in that order.
Hopefully, the order of your printed strings is a mystery no more...
Again, this has nothing to do with Ruby. This will happen in any
procedural programming language that I can think of...