Clarification on the Ruby << Operator

前端 未结 5 1368
春和景丽
春和景丽 2021-01-11 09:22

I am quite new to Ruby and am wondering about the << operator. When I googled this operator, it says that it is a Binary Left Shift Operator given this ex

5条回答
  •  忘掉有多难
    2021-01-11 09:59

    << is an operator that is syntactic sugar for calling the << method on the given object. On Fixnum it is defined to bitshift left, but it has different meanings depending on the class it's defined on. For example, for Array it adds (or, rather, "shovels") the object into the array.

    We can see here that << is indeed just syntactic sugar for a method call:

    [] << 1   # => [1]
    [].<<(1)  # => [1]
    

    and thus in your case it just calls << on @unique, which in this case is an Array.

提交回复
热议问题