Home > other >  what is [] operator in Ruby
what is [] operator in Ruby

Time:10-23

I don't get it that [] is an operator in ruby. I was wondering that if [] is an operator then what are these parenthesis {} & (). Are these also operators?

What I know is that these symbols are used by the language parser for interpreting/compiling code.

CodePudding user response:

It depends if you're talking about array literals or those brackets used for getting or assigning values from/to arrays or hashes.

As a literal, [] is just an array literal, shorthand for writing Array.new. You also asked about {}, which is a hash literal, i.e. shorthand for writing Hash.new. Parentheses are not literals (or 'operators' for that matter) – they're used to group things.

As an 'operator' for getting or assigning values, as others have pointed out in the comments, [] isn't special or conceptually different from other 'operators'.

In the same way 2 3 is sugar for writing 2. (3), writing array[0] is sugar for writing array.[](0).

The reason this works is that arrays have a method that's literally called []. You can find it by getting all the methods on an array:

[].methods
# => long array including :[] (and also :[]=, by the way, for assignments)

Note that the brackets in [].methods are an array literal, not an 'operator'.

I haven't looked at the implementation of any Ruby interpreters, but my guess is they see something like array[0] and convert it to array.[](0) (or at least they treat it as such). That's why this kind of sugar syntax works and looks like 'operators' even though it's all methods under the hood.

  • Related