Space before syntax breaking in ruby ​​multiplication expression

When adding some space to make the code more readable (align with the code above), I came across this:

class C def x 42 end end m=C.new 

Now this will give the "wrong number of arguments":

 mx *mx 

And this will give a "syntax error, unexpected tSTAR awaiting $ end":

 2/mx *mx 

What exactly happens in the parser here?

I tested with Ruby 1.9.2 and 2.1.5.

+5
source share
2 answers

* used both for the operator ( 42 * 42 ) and for unpacking the arguments ( myfun *[42, 42] ).

When you do:

 mx *mx 2/mx *mx 

Ruby interprets this as unpacking the arguments, not the * operator (i.e., multiplication).

If you are not familiar with it, unpacking the arguments (sometimes also called "splat" or "splats") means that you can have a function like this:

 def myfun arg1, arg2; end 

And name it as follows:

 myfun(*['Hello', 'World']) 

arg1 set to Hello , and arg2 set to World .

I believe that the rules should determine what to use:

  • Space before, but not after * → Unpacking arguments
  • Function parenthesis start → Unpacking arguments
  • Everything else → Multiplication (or rather, the * operator, since Ruby performs operator overloading).

Good recommendations:

  • Use the "optional" function in brackets when you plan to unpack the arguments;
  • use spaces before and after * when you intend to use the * (multiply) operator.

Ruby will really warn you when running ruby -v :

 test.rb|11 warning| `*' interpreted as argument prefix test.rb|12 warning| `*' interpreted as argument prefix 
+6
source

In simple language:

When you speak

 mx *mx 

It internally calls mx(*mx) ie considers *mx argument to splat mx .

Since there is a method x defined on m that takes any argument (s), you get an "invalid number of arguments" error.

When you call

 mx * mx 

It considers * as the x method, which takes an object of type "Fixnum", and in Ruby uses the * method, which takes an argument for the Fixnum class. So this is just like a challenge

 mx*(mx) 

and therefore it works!

I hope this helps you sort out the problem, if there is any clarification, feel free to comment.

+3
source

Source: https://habr.com/ru/post/1209110/


All Articles