Clarification on the Ruby << Operator

前端 未结 5 1357
春和景丽
春和景丽 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:11

    << is just a method. It usually means "append" in some sense, but can mean anything. For strings and arrays it means append/add. For integers it's bitwise shift.

    Try this:

    class Foo
      def << (message)
        print "hello " + message
      end
    end
    
    f = Foo.new
    f << "john" # => hello john
    

提交回复
热议问题