[](arg) in ruby class as bracket methodself. when calling instance method inside the classBut the following wouldnt work:
class Example
def [](position)
...
end
def test(position)
if [position] == 3 # doesn't work
end
end
I know it's probably because [position] might refers to creating an array with position, but is this documented anywhere?
This is because, as you suspect, [] is notation for "create array" as well, so from a syntax perspective it won't work. Ruby's parser can only tolerate so much ambiguity before it behaves unpredictably.
You must make it an explicit method call, like self[...], to differentiate between the two cases.
Your if condition translates to "if an array containing position is equal to 3...".
You can imagine that if [x] always made a method call to self[x] if you had [] defined as a method then it'd be really frustrating to make arrays in that code.
While there's no {} method, a similar ambiguity arises when using those braces:
p { x: y } # => Syntax error, expecting block
p({ x: y }) # => Hash argument
p { x } # => Block argument
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With