Ruby array


Release date:2023-10-28 Update date:2023-10-31 Editor:admin View counts:378

Label:

Ruby array

The Ruby array is an ordered integer index collection of any object. Each element in the array is associated with an index and can be retrieved by theindex.

The index of the array starts at 0, as in C or Java. The index of a negativenumber is counted relative to the end of the array, that is, an index of-1 represents the last element of the array,-2 represents the penultimate element of the array, and so on.

Ruby arrays can store things such as StringIntegerFixnumHashSymbol wait for someone, or even someone else. Array object.

The Ruby array does not need to specify a size, and the Ruby array grows automatically when elements are added to the array.

Create an array

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

names=Array.new

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

names=Array.new(20)

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

Example

#!/usr/bin/rubynames=Array.new(20)putsnames.size#return
20putsnames.length#return 20

The output of the above instance is as follows:

20
20

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

Example

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

The output of the above instance is as follows:

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

You can also use the new each element is populated with the results of the calculation in the block

Example

#!/usr/bin/rubynums=Array.new(10){ \|e\|e=e*2}puts"#{nums}"

The output of the above instance is as follows:

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

There is another method for arrays, ``[] `` , 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, there can be one that only receives a single parameter Array method, which uses a range as a parameter to create an array of numbers

Example

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

The output of the above instance is as follows:

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

Array built-in method

We need an instance of the Array object to call the Array method. The following is how to create an instance of an Array object:

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

This returns a new array populated with the given object. Now, using the created object, we can call any available method. For example:

Example

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

The output of the above instance is as follows:

6

Here are the common array methods (assuming array It’s a Array object):

Serial number

Method & description

1

Array & other_array returns a new array containing elements common to both arrays without repetition.

2

Array * int [or] array * Str returns a new array created by concatenating the int copy of self. With the String parameter, it is equivalent to self.join (str).

3

Array + other_array returns a new array that is created by concatenating twoarrays.

4

Array-other_array returns a new array that removes a copy of the item that appears in the other_array from the initial array.

5

Str < = > other_str compares str to other_str and returns-1 (less than), 0 (equal to), or 1 (greater than). Comparisons are case sensitive.

6

Array | other_array returns a new array by adding other_array to the array, removing duplicates.

7

Array << obj appends the given object to the end of the array. The expression returns the array itself, so several attachments can be joined together.

8

Array < = > other_array returns an integer (- 1, 0, or + 1) if the array is less than, equal to, or greater than other_array.

9

Array = = other_array if two arrays contain the same number of elements, andeach element is equal to the corresponding element in the other array (according to Object.==), then the two arrays are equal.

10

Array [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, or a subarray of elements from start to length, or a subarray specified by range. A negative index counts from the end of the array (-1 is the last element). If the index (or start index) exceeds the range, nil is returned.

11

Array [index] = obj [or] Array [start, length] = obj or an_array or nil [or]Array [range] = obj or an_array or nil sets the element indexed to index, either replacing a subarray of elements from start to length, or replacing asubarray specified by range. If the index is larger than the current capacity of the array, the array grows automatically. Negative indexes are counted 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 the self.

12

Array.abbrev (pattern = nil) calculates an explicit collection of abbreviations for strings in self. If you pass a pattern or a string, only consider what happens when the string matches the pattern or starts with thestring.

13

Array.assoc (obj) searches for an array whose elements are also arrays, using obj.== to compare obj with the first element of each contained array. If there is a match, the first contained array is returned, and if no match is found, nil is returned.

14

Array.at (index) returns the element with an index of index. A negative index counts from the end of the self. Returns nil if the index is out of range.

15

Array.clear removes all elements from the array.

16

Array. compact { |item| block } [or] array. map { |item| block } is call block once for each element in self. Create a new array containing the values returned by the block.

17

Array. complete! { |item| block } [or] array. map! { |item| block } is Each element in self calls a block once, replacing the element with the value returned by the block.

18

Array.compact returns a copy of self, removing all nil elements.

19

Array.compact! Removes all nil elements from the array. Returns nil if thereis no change.

20

Array.concat (other_array) appends elements from other_array to self.

21

Array. delete (obj) [or] array. delete (obj) {block} Remove from self equal to obj The item of. If no equal item is found, nil is returned. If no equal item is found and an optional code block is provided, the result of the block is returned.

22

Array.delete_at (index) deletes the element at the specified index and returns it. If index is out of range, nil is returned.

23

array.delete_if { |item| block } When block is true, delete each element of self.

24

array.each { |item| block } Call block once for each element in self, passing that element as a parameter.

25

Array.each_ Index { |index| block } is the same as Array # each, but passes the element’s. Idex, rather than passing the element itself.

26

Array.empty? Returns true if the array itself does not contain an element.

27

Array.eql? (other) returns true if array and other are the same object, or if both arrays have the same contents.

28

array.fetch(index) [or] array.fetch(index, default) [or] array.fetch(index) { |index| block } Attempt to return the element at position index. If the index is located outside the array, the first form will throw an IndexError exception, the second form will return default, and the third form will return the value passed in to the index by calling block. Negative indices are counted from the end of the array.

29

range) [or] array.fill { |index| block } [or] array.fill(start [, length] ) { |index| block } [or] array.fill(range) { |index| block } The first three forms set the selected element of self as obj. Starting with nil is equivalent to zero. The length of nil is equivalent to self length. The last three forms fill the array with the values of the block. The block is passed through an absolute index with each element being filled.

30

array.first [or] Array.first (n) returns the first element or the first n elements of the array. If the array is empty, the first form returns nil andthe second form returns an empty array.

31

Array.flatten returns a new array, which is an one-dimensional flattened array (recursive).

32

Array.flatten! Flatten the array. Returns nil if there is no change. (the array does not contain sub arrays. )

33

Array.frozen? If array is frozen (or temporarily frozen while sorting), trueis returned.

34

Array.hash calculates the hash code of the array. Two arrays with the same content will have the same hash code.

35

Array.include? (obj) returns true if the self contains obj, otherwise returns false.

36

Array.index (obj) returns the index of the first object in the self equal toobj. Returns nil if no match is found.

37

Array.indexes (i1, i2,… IN) [or] Array.indices (i1, i2,… IN) this methodis obsolete in the latest version of Ruby, so use Array#values_at.

38

Array.indices (i1, i2,… IN) [or] Array.indexes (i1, i2,… IN) this methodis obsolete in the latest version of Ruby, so use Array#values_at.

39

Array.insert (index, obj…) insert a given value before the element of a given index, and the index can be negative.

40

Array.inspect creates a printable version of the array.

41

Array.join (sep=$,) returns a string that is created by converting each element of the array to a string and delimiting it with sep.

42

array.last [or] Array.last (n) returns the last element of self. If the array is empty, the first form returns nil.

43

Array.length returns the number of elements in the self. It could be zero.

44

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

45

array.map! { |item| block } [or] array.collect! { |item| block } call block once for each element of the array, replacing the element with the value returned by the block.

46

Array.nitems returns the number of non-nil elements in the self. It could bezero.

47

Array.pack (aTemplateString) compresses the contents of the array into binary sequences according to the instructions in aTemplateString. Instructions A, a, and Z can be followed by a number that represents the width of the result field. The remaining instructions can also have a numberthat represents the number of array elements to be converted. If the numberis an asterisk (*), all remaining array elements are converted. Any instruction can be followed by an underscore (_), indicating that the specified type uses the local size of the underlying platform, otherwise a consistent size independent of the platform. Spaces are ignored in the template string.

48

Array.pop removes the last element from the array and returns it. Returns nil if array is empty.

49

Array.push (obj,…) appends the given obj to the end of the array. The expression returns the array itself, so several attachments can be joined together.

50

Array.rassoc (key) searches for an array whose elements are also arrays, using = = to compare key with the second element of each contained array. Ifit matches, the first contained array is returned.

51

array.reject { |item| block } returns a new array containing array items when block is not true.

52

array.reject! { |item| block } When the block is true, delete the element from the array, and return nil if there are no changes. Equivalent to Array # delete_ If.

53

Array.replace (other_array) replaces the content of array with the content of other_array and truncates or expands it if necessary.

54

Array.reverse returns a new array containing elements of the array in reverse order.

55

Array.reverse! Reverse the array.

56

array.reverse_each { |item| block } same as Array # each, but reverse the array.

57

Array.rindex (obj) returns the index of the last object in the array equal to obj. If no match is found, nil is returned.

58

array.select { |item| block } call the block that passes in consecutive elements from the array and returns an array containing the elements when the block returns a true value.

59

Array.shift returns the first element of self and removes it (moving all other elements down one bit). Returns nil if the array is empty.

60

Array.size returns the length of the array (number of elements). An alias for length.

61

array.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 index, or a subarray of elements from start to length, or a subarray specified by range. Negative index counts from the end of the array (-1 is the last element. If the index (or starting index) is out of range, nil is returned.

62

Array.slice! (index) [or] Array.slice! (start, length) [or] Array.slice! (range) removes the element specified by index (the length is optional) or range. Returns the deleted object, subarray, or nil if index is out of range.

63

array.sort [or] array.sort { | a,b | block } Returns a sorted array.

64

array.sort! [or] array.sort! { | a,b | block } Sort the array.

65

Array.to_a returns self. If called on a subclass of Array, the receive parameter is converted to an Array object.

66

Array.to_ary returns self.

67

Array.to_s returns self.join.

68

Array.transpose assumes that self is an array of arrays and replaces rows and columns.

69

Array.uniq returns a new array, removing duplicate values from array.

70

Array.uniq! Removes repeating elements from the self. If there is no change (that is, no duplicates are found), nil is returned.

71

Array.unshift (obj,…) put the object in front of the array and move the other elements up one bit.

72

Array.values_at (selector,…) returns an array containing the elements in the self that correspond to the given selector (s). The selector can be an integer index or a range.

73

array.zip(arg, …) [or] array.zip(arg, …){ | arr | block } convert any parameters into an array, and then merge the elements of the array with the corresponding elements in each parameter.

Array pack instruction

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

Instruction

Description

@

Move to absolute position.

A

ASCII string (padding space,count is the width).

A

ASCII string (padding null,count is the width).

B

Bit string (descending)

B

Bit string (ascending order).

C

Unsigned characters.

C

Characters.

D, d

Double precision floating point number, native format.

E

Double precision floating point numbers, little-endian byte order.

E

Single precision floating point number, little-endian byte order.

F, f

Single precision floating point number, native format.

G

Double precision floating point numbers, network (big-endian) byte order.

G

Single-precision floating point numbers, network (big-endian) byte order.

H

Hexadecimal string (high order first).

H

Hexadecimal string (low order first).

I

Unsigned integer.

I

Round number.

L

Unsigned long.

L

Long .

M

Reference printable, MIME code.

M

Base64 encoded string.

N

Long,network (big-endian) byte order.

N

Short,network (big-endian) byte order.

P

Point to a structure (a fixed-length string).

P

Point to an empty end string.

Q, q

64 digits.

S

Unsigned short.

S

Short .

U

UTF-8 .

U

UU encoded string.

V

Long,little-endian byte order.

V

Short,little-endian byte order.

W

The integerfnm compressed by BER.

X

Skip one byte backward.

X

Null bytes.

Z

Same as a, except that null will be added * .

Example

Try the following example to compress all kinds of data.

Example

a=["a","b","c"]n=[65,66,67]putsa.pack("A3A3A3")#=> "a b c
"putsa.pack("a3a3a3")#=>
"a\000\000b\000\000c\000\000"putsn.pack("ccc")#=> "ABC"

The output of the above instance is as follows:

a  b  c
abc
ABC

Powered by TorCMS (https://github.com/bukun/TorCMS).