Home »
Ruby programming
Array.pack() Method with Example in Ruby
Ruby Array.pack() Method: Here, we are going to learn about the Array.pack() Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 15, 2020
Array.pack() Method
In this article, we will study about Array.pack() Method. You all must be thinking the method must be doing something which is related to finding values from the Array instance. It is not as simple as it looks. Well, we will figure this out in the rest of our content. We will try to understand it with the help of syntax and demonstrating program codes.
Method description:
This method is a public instance method and defined for the Array class in Ruby's library. This method works in a way that it packs the objects of Array instance into a binary sequence. This sequence depends upon the directives present in the aTemplateString. These directives can be "A", "a" or "Z" which can be followed by count which provides you the width of the resulting field. The directives which are left can also take a count which indicates the number of Array elements to be converted. If the count is an ("*") then all the elements will be converted.
Syntax:
array_instance.pack(aTemplateString) -> aBinaryString
Argument(s) required:
This method takes a template string as an argument. You can provide atmost one template String.
Example 1:
=begin
Ruby program to demonstrate pack method
=end
# array declaration
table = ["Geeta","Sabita","Monica","Syresh","Kamish","Punish"]
puts "Array pack implementation"
puts table.pack("A3A3A3A3A3A3")
puts "Array instance : #{table}"
Output
Array pack implementation
GeeSabMonSyrKamPun
Array instance : ["Geeta", "Sabita", "Monica", "Syresh", "Kamish", "Punish"]
Explanation:
In the above code, you can observe that we are creating Binary String from the Array instance with the help of the Array.pack() method. The method is returning a String which has been packed using TemplateString "A3A3A3A3A3A3".
Example 2:
=begin
Ruby program to demonstrate pack method
=end
# array declaration
table = ["fatima","Sabita","Monica","Syresh","Kamish","Punish"]
puts "Array pack implementation"
puts table.pack("a3a3a3")
puts "Array instance : #{table}"
Output
Array pack implementation
fatSabMon
Array instance : ["fatima", "Sabita", "Monica", "Syresh", "Kamish", "Punish"]
Explanation:
In the above code, you can observe that we are creating Binary String from the Array instance with the help of the Array.pack() method. The method is returning a String which has been packed using TemplateString "a3a3a3".