Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't omit `self` when using bracket method in a class

Tags:

ruby

  1. I know we can define [](arg) in ruby class as bracket method
  2. I know we can omit self. when calling instance method inside the class

But 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?

like image 469
smilence Avatar asked Sep 10 '26 15:09

smilence


1 Answers

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
like image 153
tadman Avatar answered Sep 13 '26 15:09

tadman