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:
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:
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:
=> "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:
=> [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.
=> [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 << 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:
=> "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.