Ruby parens-free function calls [was Re: Accessing parent objects]

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Mar 26 06:43:32 EDT 2018


On Sun, 25 Mar 2018 19:16:12 -0700, Rick Johnson wrote:

> On Sunday, March 25, 2018 at 5:57:28 PM UTC-5, Steven D'Aprano wrote:
> 
>> [supposed "fix" to the sample script snipped]
>>
>> You know Rick, every time I start to think that talking to you like an
>> adult might result in a productive and intelligent conversation, you
>> pull a stunt like this.  Once I recover from laughing at your inability
>> to read a simple eight line Ruby script, and then laughing even harder
>> at your inability to tell the difference between a string in Ruby and
>> an actual function call, I *might* come back and read the rest of your
>> post.

[...]

> If not, then explain to this group exactly how i failed.


Rick, you're supposedly familiar with Ruby. And yet, you didn't notice 
that your supposed "fix" didn't touch any executable code, all it did was 
modify the strings being printed. Because of this "fix", the printed 
strings no longer match the code being executed, but the strange, 
inconsistent behaviour still occurs.

For the benefit of those who aren't Ruby experts, the code I used before 
(see below) defines a function called "a", then prints four ways of 
calling that function that differ only in whitespace. For example:

    print "a + b => ", (a + b), "\n"


prints the string "a + b", then calls a and adds b using the same syntax 
as that shown in the string, then prints a newline.

The kicker is that out of these four legal, parenthesis-free ways of 
calling function a, *three* of them interpret the expression as:

    call a with no arguments
    then add b using the binary plus operator

but the last, differing only in whitespace, interprets it as:

    call a with a single argument, unary-plus b


Here's the code again:


# --- cut ---
def a(x=4)
    x+2
end

b = 1
print "a + b => ", (a + b), "\n"
print "a+b   => ", (a+b), "\n"
print "a+ b  => ", (a+ b), "\n"
print "a +b  => ", (a +b), "\n"
# --- cut ---

and your "fix" was to modify the *strings* without touching the actual 
function calls. Well done Rick.

Of course we can solve the problem by always using parentheses when 
making function calls. But that misses the point that Ruby allows this 
inconsistency in the first place.



-- 
Steve




More information about the Python-list mailing list