0

I write a method.

def additionner (x,y) 

  puts (x * y) 

end 

additionner(2,7)

It works, but if I make a space after calling the method, it doesn’t work, why? Note that there is no difference wether there is a space between the method name and the parenthesis inside the definition of the method.

def additionner (x,y)

  puts (x * y)

end

additionner (2,7)

(repl):4: syntax error, unexpected ‘,’, expecting ‘)’ additionner (2,7)

in version: ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]

kouty
  • 320
  • 8
  • 17
  • 2
    That's just the way ruby was designed. The reason is likely because parens on function calls and definitions are optional, so omitting them makes it ambiguous that it's a function call with two params. For the definition, the space is unambiguous likely because of the `def` keyword. – ggorlen Sep 02 '19 at 22:18
  • @ggorlen So the space is ambiguous when "written" after calling the method and the parentheses don't not desambigue it. – kouty Sep 02 '19 at 22:30
  • Yes, because parenthesis are also a tuple in addition to parameter lists. See the dupe link. Ruby doesn't know if you're trying to call the method with one tuple literal or with a parameter list. Anyway, there's never reason to put spaces between functions and their parameter lists, so it's sort of an academic question. – ggorlen Sep 02 '19 at 22:37
  • @ggorlen Yes I already read it. Thank you. – kouty Sep 02 '19 at 22:39
  • Also see https://stackoverflow.com/questions/41821628/ruby-how-can-i-kill-warning-interpreted-as-argument-prefix/41822037#41822037 – mu is too short Sep 02 '19 at 22:42
  • 1
    Parentheses can be used for expression grouping or calling methods. When you say `m(a, b)`, they're method calling parentheses; when you say `m (a, b)`, they're expression grouping parentheses. Then, since `a, b` isn't an expression (i.e. there's no comma operator in Ruby), `m (a, b)` is a syntax error. – mu is too short Sep 02 '19 at 22:46
  • 1
    @muistooshort It's perfectly makes sense now. It is different than the answer in the original post I duplicated. Because from the answer there, it seems that space is a parenthesis so space + content + ) would be good and there isn't. With your answer, logically it's clear. – kouty Sep 02 '19 at 23:03
  • 1
    Thanks. The one I answered was marked as a duplicate so I figured that question is more canonical than the one I answered. Shame that the "This question already has an answer here:" links don't go both ways – mu is too short Sep 02 '19 at 23:11
  • So it seems they are linked both ways but the back-links are sort of hidden in the "Linked" sidebar box. – mu is too short Sep 02 '19 at 23:27

0 Answers0