Crystal: Setter method receiving multiple arguments

Created on 23 Mar 2018  路  7Comments  路  Source: crystal-lang/crystal

A setter method (ending in =) can be defined having multiple arguments:

def foo=(a, b)
  pp a, b
end

But such a method can't be called. Obviously foo = 1, 2 won't work because it is interpreted as two expressions. Adding parenthesis around the arguments foo=(1, 2) raises a syntax error: unterminated parenthesized expression probably because ( after = is not recognized as parenthesis of a call.

I'm not sure if it should be supported that setter methods can receive multiple arguments. It seems like this is too complicated and unnecessary.
But if you can't call such a method with more than one argument, it would make sense to raise a syntax error for the method definition with multiple arguments as well.

bug accepted compiler

Most helpful comment

Oh yeah, I see what the syntax is doing now, yeah the second example works (and should) in crystal. The first one used to work, but I removed implicit arrays in https://github.com/crystal-lang/crystal/pull/4824.

All 7 comments

Yeah, it should probably be disallowed. PRs are welcome :-)

I think in ruby there is something called greedy matches. This means that it will turn the args into an array. This does not get around arity but it does make things like this work.
Ruby: https://eval.in/1035570

def setter=(a)
  puts a
end
setter = 1, 2

Also because of method sending this works which I dont know if we want in Crystal but it would be awesome.
Ruby: https://eval.in/1035572

def setter=(a)
  puts a
end
setter, a = 1, 2

...how is that in any way awesome?

Also, your examples are all wrong, they just set local variables. You need to use self.setter

And the second snippet, using self.setter, already works in Crystal

I missed self when I was simplifying the examples.

I did not know the second example would work in Crystal I am really glad it does though.

Oh yeah, I see what the syntax is doing now, yeah the second example works (and should) in crystal. The first one used to work, but I removed implicit arrays in https://github.com/crystal-lang/crystal/pull/4824.

Yeah I was more just pointing it out first example. I don't really have any opinion on the implicit array but I do like the second example.

Was this page helpful?
0 / 5 - 0 ratings