Ruby

The Binary Left Shift Operator in Ruby

The binary left shift operator in Ruby is represented by the double angle bracket (<<). When used with integers, it shifts the bits of the left operand several positions to the left as specified by the right operand.

In this tutorial, we will discuss Ruby's various uses and functionalities of the binary left-shift operator.

Syntax
The following shows the syntax of the binary left shift operator in Ruby:

number << position

The number parameter denotes the number whose bits we wish to shift. The position parameter represents the number of positions we wish to shift the bits of the specified number.

After bit shifting, the operator will return an integer equivalent to the decimal value of the specified number.

Example Demonstration

The following shows an example of the usage of the left shift operator with a set of integer values:

irb(main):001:0> puts 10 << 2
40

String Concatenation

We can also use the left shift operator to concatenate two strings. The method will join the provided string and modify the original string as shown:

irb(main):035:0> greet = 'Hi.'
=> "Hi."
irb(main):036:0> greet << "Hi to you too."
=> "Hi.Hi to you too."

Array Appending Using the Left Shift Operator

We can also use this operator to append a value to an array, as demonstrated in the example below:

irb(main):037:0> arr = [1,2,3]
=> [1, 2, 3]
irb(main):038:0> arr << 4
=> [1, 2, 3, 4]

In this case, the method works like the Array#push method. You can also provide another array to push to an existing one.

irb(main):039:0> arr = [1,2,3]
=> [1, 2, 3]
irb(main):040:0> arr << [4,5,6]
=> [1, 2, 3, [4, 5, 6]]

Method Definition

We can also use the << operator to define methods within a Class in Ruby. Take the example shown below:

class Person
    class << self
        def greet
            'hi.'
        end
    end
end

In this case, we should define a Person’s class with a method that prints “hi” to the console.

We can call the method:

irb(main):057:0> Person.greet
=> "hi."

Conclusion

We discussed the various ways you can use the left shift operator in Ruby to perform various actions such as string concatenation and more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list