Some related methods of using arrays in Ruby

Time:2022-5-18

 RubyarrayIs orderly, any object?? A collection of integer indexes. Each element in the array is associated and referred to by an index.

Array subscripts start with 0, such as C or Java. Negative index assumes the end of the array – that is, – 1 represents the array index of the last element, – 2 is the next element of the last element in the array, and so on.

Ruby arrays can hold objects such as strings, integers, long integers, hashes, symbols, and even other array objects. Ruby arrays are not as strict as arrays in other languages. Ruby arrays grow automatically and add elements at the same time.
Create array:

There are many ways to create or initialize an array. One way is the new class method:

?
1
names = Array.new

You can set the size of an array. When creating an array:

?
1
names = Array.new(20)

Array names now has a size or length of 20 elements. You can return the size or length of an array:

?
1
2
3
4
5
#!/usr/bin/ruby
 
names = Array.new(20)
puts names.size # This returns 20
puts names.length # This also returns 20

This will produce the following results:

?
1
2
20
20

You can specify each element in a value array as follows:

?
1
2
3
4
5
#!/usr/bin/ruby
 
names = Array.new(4, "mac")
 
puts "#{names}"

This will produce the following results:

?
1
macmacmacmac

You can also use the new block, which will calculate and fill each element:

?
1
2
3
4
5
#!/usr/bin/ruby
 
nums = Array.new(10) { |e| e = e * 2 }
 
puts "#{nums}"

This will produce the following results:

?
1
024681012141618

There is another method, array, []. Its working principle is as follows:

?
1
nums = Array.[](1, 2, 3, 4,5)

Another form of array creation is as follows:

?
1
nums = Array[1, 2, 3, 4,5]

The kernel module, the core of ruby, has an array method that accepts only one parameter. Create an array of numbers as parameters within the scope of the method:

?
1
2
3
4
5
#!/usr/bin/ruby
 
digits = Array(0..9)
 
puts "#{digits}"

This will produce the following results:

?
1
0123456789

Array built-in method:

We need an instance of the array object calling the array method. As we can see, the following is the way to create an instance of the array object:

?
1
Array.[](...) [or] Array[...] [or] [...]

This will return a new array to fill the given object. Now, using the created object, we can call any available instance method. For example:

?
1
2
3
4
5
6
7
#!/usr/bin/ruby
 
digits = Array(0..9)
 
num = digits.at(6)
 
puts "#{num}"

This will produce the following results:

?
1
6

For example:

Try the following example to collect various data.

?
1
2
3
4
5
a = [ "a", "b", "c" ]
n = [ 65, 66, 67 ]
puts a.pack("A3A3A3"#=> "a b c "
puts a.pack("a3a3a3"#=> "a\000\000b\000\000c\000\000"
puts n.pack("ccc")   #=> "ABC"

This will produce the following results:

?
1
2
3
a b c
abc
ABC