Home »
Ruby Tutorial
Ruby Array.pack() Method
By IncludeHelp Last updated : December 01, 2024
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.
Description and Usage
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
Parameters
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".