Clarification on the Ruby << Operator

前端 未结 5 1320
春和景丽
春和景丽 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 10:09

    In Ruby, operators are just methods. Depending on the class of your variable, << can do different things:

    # For integers it means bitwise left shift:
    5 << 1  # gives 10
    17 << 3 # gives 136
    
    # arrays and strings, it means append:
    "hello, " << "world"   # gives "hello, world"
    [1, 2, 3] << 4         # gives [1, 2, 3, 4]
    

    It all depends on what the class defines << to be.

提交回复
热议问题