home PYTHONJAVA
 

Ruby Array(Array)

A Ruby array is an ordered set of integer indexes for any object. Each element in the array is associated with an index and can be retrieved through an index.

The index of the array starts at 0, which is the same as in C or Java. A negative number is counted relative to the end of the array, that is, the index is -1 for the last element of the array, -2 is the second-to-last element of the array, and so on.

Ruby arrays can store objects such as String, Integer, Fixnum, Hash, Symbol, and so on, and can even be other Array objects.

Ruby arrays do not need to be sized, and Ruby arrays grow automatically when you add elements to an array.

Create an array

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

names = Array.new

You can set the size of the array while creating the array:

names = Array.new( 20)

Array names is 20 elements in size or length. You can use the size or length method to return the size of the array:

Instance

#!/usr/bin/ruby names = Array.new(20) puts names.size # return 20 puts names.length # return 20

The above example runs the output as:

20
20

You can assign a value to each element in the array as follows:

Instance

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

The above example runs the output as:

["mac",  "mac", "mac", "mac"]

You can also use blocks with new, each of which is populated with calculations in the block:

Instance

#!/usr/bin/ruby nums = Array< Span class="hl-code">.new(10) { | e| e = e * 2 } puts "#{nums}"

The above example runs the output as:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Arrays have another method, [], as follows:

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

Another form of array creation is as follows:

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

In the Ruby core module, you can have an Array method that takes only a single parameter, which uses a range as a parameter to create an array of numbers:

Instance

#!/usr/bin/ruby digits = Array(0..9) puts "#{digits}"

The above example runs the output as:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array built-in method

We need to have an instance of the Array object to call the Array method. Here's how to create an Array object instance:

Array.[](...) [or] Array[...] [or] [...]

This will return a new array populated with the given object. Now, using the created object, we can call any of the available methods. For example:

Instance

#!/usr/bin/ruby digits = Array(0..9) num = digits.at(6) puts "#{num}"

The above example runs the output as:

6

The following is a public array method (assuming array is an Array object):

serial numbermethod & description
1array & other_array
Returns a new array containing the elements common to both arrays, with no repetition.
2array * int [or] array * str
returns a new array created by concatenating a copy of self 's int . With the String argument, it is equivalent to self.join(str).
3array + other_array
Returns a new array created by concatenating two arrays to produce a third array.
4array - other_array
Returns a new array that removes items from other arrays that appear in other_array A copy.
5str <=> other_str
Compare str with other_str and return -1 (less than), 0 (equal) or 1 (greater than). The comparison is case sensitive.
6array | other_array
Returns a new array by adding other_array to array, removing duplicates.
7array << obj
Appends the given object to the end of the array. This expression returns the array itself, so several additions can be joined together.
8array <=> other_array
If the array is less than, equal to, or greater than other_array, return an integer (-1, 0 or +1).
9array == other_array
If two arrays contain the same number of elements, and each element corresponds to another array The elements are equal (according to Object.==), then the two arrays are equal.
10array[index] [or] array[start, length] [or]
Array[range] [or] array.slice(index) [or]
Array.slice(start, length) [or] array.slice(range)

Returns an element with index index or returns from start A subarray of length elements, or a subarray specified by range. A negative index starts counting from the end of the array (-1 is the last element). Returns nil if index (or start index) is out of range.
11array[index] = obj [or]
Array[start, length] = obj or an_array or nil [or]
Array[range] = obj or an_array or nil

Set the element with index index, or replace it from start until length a subarray of elements, or replace the subarray specified by range. If the index is greater than the current capacity of the array, the array grows automatically. Negative indexes start counting from the end of the array. Insert an element if length is zero. If nil is used in the second or third form, the element is removed from self.
12array.abbrev(pattern = nil)
Calculate an abbreviated set of abbreviations for strings in self . If you pass a pattern or a string, only consider the case when the string matches the pattern or starts with the string.
13array.assoc(obj)
Search for an array whose elements are also arrays, using obj.== to put obj with each The first element of the array is compared. Returns the first containing array if it matches, or nil if no match is found.
14array.at(index)
Returns an element indexed to index. A negative index starts counting from the end of self. Returns nil if the index is out of range.
15array.clear
Remove all elements from the array.
16array.collect { |item| block } [or]
Array.map { |item| block }

Calls block once for each element in self. Create a new array containing the values ​​returned by the block.
17array.collect! { |item| block } [or]
Array.map! { |item| block }

Invoke block once for each element in self, replacing the element with block The value returned.
18array.compact
Returns a copy of self and removes all nil element.
19array.compact!
Remove all nil elements from the array. Returns nil if there is no change.
20array.concat(other_array)
Add elements from other_array to self.
21array.delete(obj) [or]
Array.delete(obj) { block }

Remove items equal to obj from self. If no equality is found, nil is returned. If no equality is found and the optional code block is given, the result of block is returned.
22array.delete_at(index)
Remove the element at the specified index and return it. If the index is out of range, nil is returned.
23array.delete_if { |item| block }
When block is true, delete Each element of self.
24array.each { |item| block }
Invoke once for each element in self i>block, passing this element as a parameter.
25array.each_index { |index| block }
Same as Array#each, but passing index of the element > instead of passing the element itself.
26array.empty?
Returns true if the array itself does not contain an element.
27array.eql?(other)
If array and other are Returns true if the same object, or two arrays, have the same content.
28array.fetch(index) [or]
Array.fetch(index, default) [or]
Array.fetch(index) { |index| block }

Try to return the element at position index. If index is outside the array, the first form will throw an IndexError exception, and the second form will return default, the third form It will return the value of the index passed to block. Negative index counts from the end of the array.
29array.fill(obj) [or]
Array.fill(obj, start [, length]) [or]
Array.fill(obj, range) [or]
Array.fill { |index| block } [or]
Array.fill(start [, length] ) { |index| block } [or]
Array.fill(range) { |index| block }

The three selected elements of self are obj. Starting with nil is equivalent to zero. The length of nil is equivalent to self.length. The last three forms are populated with the value of the block array. block is passed through an absolute index with each element being filled.
30array.first [or]
Array.first(n)

returns the first element of the array or the first n elements. If the array is empty, the first form returns nil, and the second form returns an empty array.
31array.flatten
Returns a new array, which is a one-dimensional flattened array (recursive).
32array.flatten!
Flatten array. Returns nil if there is no change. (Arrays do not contain subarrays.)
33array.frozen?
If true if array is frozen (or temporarily frozen when sorting) .
34array.hash
Calculate the hash code of the array. Two arrays with the same content will have the same hash code.
35array.include?(obj)
If self contains obj , return true, otherwise return false.
36array.index(obj)
Returns the self of the first object equal to obj >index. Returns nil if no match is found.
37array.indexes(i1, i2, ... iN) [or]
Array.indices(i1, i2, ... iN)

This method is deprecated in the latest version of Ruby, so use Array#values_at.
38array.indices(i1, i2, ... iN) [or]
Array.indexes(i1, i2, ... iN)

This method is deprecated in the latest version of Ruby, so use Array#values_at.
39array.insert(index, obj...)
Before the given index element Insert the given value and index can be negative.
40array.inspect
Create a printable version of the array.
41array.join(sep=$,)
returns a string by converting each element of the array to a string, And created using sep separation.
42array.last [or] array.last(n)
returns the last element of self. If the array is empty, the first form returns nil.
43array.length
Returns the number of elements in self. May be zero.
44array.map { |item| block } [or]
Array.collect { |item| block }

Calls block once for each element of self. Create a new array containing the values ​​returned by the block.
45array.map! { |item| block } [or]
Array.collect! { |item| block }

Calls block once for each element of array, replacing the element with the value returned by block.
46array.nitems
Returns the number of non-nil elements in self. May be zero.
47array.pack(aTemplateString)
Compresses the contents of the array into a binary sequence based on the instructions in aTemplateString. Instructions A, a, and Z can be followed by a number indicating the width of the resulting field. The remaining instructions can also have a number indicating the number of array elements to be converted. If the number is an asterisk (*), all remaining array elements will be converted. Any instruction can be followed by an underscore (_) indicating that the specified type uses the native size of the underlying platform, otherwise a platform-independent size is used. Spaces in the template string are ignored.
48array.pop
Remove the last element from array and return it. Returns nil if array is empty.
49array.push(obj, ...)
Appends the given obj to the end of the array. This expression returns the array itself, so several additions can be joined together.
50array.rassoc(key)
Search for an array whose elements are also arrays, using == to put key Compare with the second element of each contained array. Returns the first containing array if it matches.
51array.reject { |item| block }
Returns a new array containing array items when block is not true.
52array.reject! { |item| block }
Delete from array when block is true The element, if there is no change, returns nil. Equivalent to Array#delete_if.
53array.replace(other_array)
Replace the contents of array with other_array > The contents are truncated or expanded as necessary.
54array.reverse
Returns a new array containing the array elements in reverse order.
55array.reverse!
Reverse array.
56array.reverse_each {|item| block }
Same as Array#each, but with array reverse.
57array.rindex(obj)
Returns the index of the last object in array equal to obj. If no match is found, nil is returned.
58array.select {|item| block }
calls a block that passes in consecutive elements from the array, returns an array containing the block The element when the true value.
59array.shift
Returns the first element of self and removes the element (puts all The other elements move down one bit). Returns nil if the array is empty.
60array.size
Returns the length of array (the number of elements). An alias for length.
61array.slice(index) [or] array.slice(start, length) [or]
Array.slice(range) [or] array[index] [or]
Array[start, length] [or] array[range]

Returns an element with an index of index or returns from start until A subarray of length elements, or a subarray specified by range. A negative index starts counting from the end of the array (-1 is the last element). Returns nil if index (or start index) is out of range.
62array.slice!(index) [or] array.slice!(start, length) [or]
Array.slice!(range)

Remove the index (length is optional) or range specified element. Returns the deleted object, subarray, or nil if index is out of range.
63array.sort [or] array.sort { | a,b | block }
Returns a sorted array.
64array.sort! [or] array.sort! { | a,b | block }
Sort the array.
65array.to_a
Return self. If called on a subclass of Array, converts the receive parameter to an Array object.
66array.to_ary
returns self.
67array.to_s
Returns self.join.
68array.transpose
Assume that self is an array of arrays and replaces rows and columns.
69array.uniq
Returns a new array, removing duplicate values ​​from array.
70array.uniq!
Remove duplicate elements from self. If there is no change (that is, no duplicates are found), then nil is returned.
71array.unshift(obj, ...)
Place the object in front of the array and move the other elements up one bit.
72array.values_at(selector,...)
returns an array containing the self with the given selector< /i>(one or more) corresponding elements. The selector can be an integer index or range.
73array.zip(arg, ...) [or]
Array.zip(arg, ...){ | arr | block }

Convert any argument to an array, then the array element corresponds to each parameter The elements are merged.

Array pack directive

The following table lists the compression instructions for the method Array#pack.

InstructionsDescription
@ Move to absolute position.
AASCII string (fill space, count is width).
aASCII string (filled with null, count is width).
BBit String (Descending)
bBit string (ascending order).
CUnsigned characters.
c characters.
D, dDouble-precision floating-point numbers, native format.
EDouble-precision floating-point numbers, little-endian byte order.
e Single-precision floating-point numbers, little-endian byte order.
F, f Single-precision floating-point numbers, native format.
GDouble-precision floating-point numbers, network(big-endian) byte order.
g Single-precision floating-point numbers, network(big-endian) byte order.
HHexadecimal string (high order first).
hhexadecimal string (lower first).
IUnsigned integer.
iInteger.
LUnsigned long.
lLong.
M references printable, MIME encoding.
mBase64 encoded string.
NLong, network(big-endian) byte order.
nShort, network(big-endian) byte order.
P points to a structure (a fixed-length string).
p points to an empty end string.
Q, q64 digits.
SUnsigned short.
sShort.
UUTF-8.
uUU encoded string.
VLong, little-endian Byte order.
vShort, little-endian Byte order.
wBER Compressed integer \fnm.
X Skips one byte backward.
xNull bytes.
Z is the same as a, except that null will be appended with *.

Instance

Try the example below to compress various data.

Instance

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"

The above example runs the output as:

a b c
Abc
ABC





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.