ruby - Why is f(arg, superfluous_arg) an ArgumentError but f (arg, superfluous_arg) a SyntaxError? -


in ruby 1.9.3, have function single argument. if call correctly, works either or without whitespace separating name , parenthesis. if pass argument, fails in 2 different ways. why?

irb(main):001:0> def f(a); a; end => nil irb(main):002:0> f(1) => 1 irb(main):003:0> f(1, 2) argumenterror: wrong number of arguments (2 1)         (irb):1:in 'f'         (irb):3         /usr/bin/irb:12:in '<main>' irb(main):004:0> f (1) => 1 irb(main):005:0> f (1, 2) syntaxerror: (irb):5: syntax error, unexpected ',', expecting ')' f (1, 2)      ^         /usr/bin/irb:12:in '<main>' irb(main):006:0> ruby_description => "ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-linux]" 

the first error:

>> f(1, 2) argumenterror: wrong number of arguments (2 1) 

...is pretty straightforward, you're passing 1 argument many.

let's concentrate on second error!

>> f (1, 2) 

this equivalent to:

>> f((1, 2)) 

which invalid syntax. because:

(1, 2) 

...isn't valid expression either. can see more this:

>> 1, 2 syntaxerror: (irb):9: syntax error, unexpected ',', expecting $end 

why f (1) work?

well (1) evaluates 1:

>> (1) => 1 

what mean?

method calls "method_name(parameter1, parameter2, …)" (with no space before opening parenthesis) or "method_name parameter1, parameter2, …" (with no parentheses @ all).

mixing spaces , parentheses lead unexpected behaviour somewhere down line, have seen.


Comments