官术网_书友最值得收藏!

Arrays

Arrays and hashes are perhaps the two data structures that will be used the most by developers who are writing the Chef code. Be it fetching attributes or values from data bags, you'll be finding these two data structures almost everywhere.

Arrays are an ordered collection of objects that can be accessed through an integer index. Each element of an array can be referenced through an index. The first element of the array is referenced through index number 0 and so on. Ruby also provides support for negative integers as indexes. -1 refers to the last element of the array, -2 is the second last element, and so on.

Unlike other languages, arrays in Ruby aren't tied to one single data type, and they aren't fixed in size either. Ruby arrays grow automatically while elements are added to it. Ruby arrays can also hold other array objects, thereby allowing us to set up multidimensional arrays.

Creating an array

There are multiple ways to create arrays.

Way 1—using the new method of the Array class:

countries = Array.new

Let's create this array with an initial size of 10:

countries = Array.new(10)

We can find the size and length of the array using the size and length methods:

#/usr/bin/env ruby
countries = Array.new(10)
puts countries.size
puts countries.length

When executed, this will produce the following result:

10
10

Let's assign some values to our array:

countries = Array.new(3, "India")

This will create a countries array with values ["India","India","India"].

Way 2—using the [] method of the Array class:

countries = Array["India","China","USA"]

Way 3—directly initializing an array using []:

countries = ["India","China","USA"]

Way 4—specifying the range as an argument to create an array:

digits = Array(0..9)

This is equivalent to saying this:

digits = Array.new(0,1,2,3,4,5,6,7,8,9)

Or it is equivalent to saying this:

digits = Array.new(10) {|x| x}

Also, it is equivalent to saying this:

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

With our array created, we can now do lot of things with it. Let's see a few operations that we'll be using most often with objects of the Array class.

Accessing elements of an array

Elements of an array can be retrieved using the #[] method. It can take either a single integer (absolute index), a range, or start element and length as arguments:

digits = [1,2,3,4,5,6,7,8,9]
digits[0] #=> 1
digits[2] #=> 3
digits[-1] #=> 9
digits [-2] #=> 8
digits [2,3] #=> [3,4,5]
digits[2..3] #=> [3,4]
digits[2..-4] #=> [3,4,5,6]

Another way to access an element of an array is to make use of the at method:

digits.at(2) => 3

If you try to access a value beyond the array boundaries, Ruby by default returns nil. However, there might be circumstances where you might want to throw away an error, or return some default value, if someone tries to access values beyond the boundaries of an array. You can make use of the fetch method for this purpose:

digits.fetch(100) #=> IndexError: index 100 outside of array bounds: -9...9
digits.fetch(100,"Out of bounds!") #=> Out of bounds!

There are two special methods, namely first and last. These methods allow you to access the first and last element of an array:

digits.first #=> 1
digits.last #=> 9

To get the first n elements of an array, make use of the take statement:

digits.take(4) #=> [1,2,3,4]

There is another method called drop, which ignores the first n elements and returns the remaining elements:

digits.drop(5) #=> [6,7,8,9]

To check whether an array has any element at all or not, use the empty? method:

digits.empty? #=> returns true if array named digits is empty or else it'll return false

To check whether a particular element is included in the array, use the include? method:

digits.include?(8) #=> returns true if array named digits contains 8 or else it'll return false

Adding elements to an array

Elements can be added to an existing array using the push method or <<.

digits = [0,1,2,3,4]
digits.push(5) #=> [0,1,2,3,5]
digits << 6 #=> [0,1,2,3,4,5,6]

To add an element to the beginning of an array, use the unshift method:

digits.unshift(9) #=> [9,0,1,2,3,4,5,6]

To add an element at a fixed location, use the insert method:

digits.insert(3,'three') #=> [9,0,1,'three',2,3,4,5,6]

We can also add multiple values, as follows:

digits.insert(3,'three','four') #=>[9,0,1,'three','four',2,3,4,5,6]

Removing elements from an array

Elements can be removed from an array using the pop method:

digits = [0,1,2,3]
digits.pop
digits #=> [0,1,2]

You can use the shift method to remove an element from the start of an array:

digits.shift #=> 0
digits #=> [1,2]

To delete an element in a particular position, you can make use of the delete_at method:

digits = [0,1,2,3]
digits.delete_at(1) #=> 1
digits #=> [0,2,3]

To delete a particular element, use the delete method:

digits = [0,1,2,2,3]
digits.delete(2) #=> 2
digits #=> [0,1,3]

If you want to remove duplicate values from an array, you can make use of the uniq method. It has two variants, uniq and uniq!. The former will return a copy of the array without duplicates, while the second one will remove the duplicate elements within the array itself:

digits = [0,1,2,2,3]
digits.uniq #=> [0,1,2,3]
digits #=> [0,1,2,2,3]
digits.uniq! #=> [0,1,2,3]
digits #=> [0,1,2,3]

Iterating over an array

There are multiple ways in which one can iterate over an array. You can make use of the loop constructs that we discussed earlier:

#!/usr/bin/env ruby
counter=0
x=[1,2,3,4]
while counter < x.length
 puts x[counter]
 counter += 1
end

However, like many other classes, the Array class includes the Enumerable module, which provides a method called each. This method defines how and which elements should be iterated. In case of arrays, you can supply a block to this method, and all the elements of the array will be yielded:

x = [1,2,3,4]
x.each {|i| puts i}

Running this piece of code gives the following output:

1
2
3
4

There is a reverse_each method as well, that as its name suggests, allows for traversal of the array in the reverse order:

x = [1,2,3,4]
x.reverse_each { |i| puts i }

Running this piece of code gives the following output:

4
3
2
1

There are times when we would like to create a new array based on the original array, but with some modifications that are consistent across all elements of the array. We can make use of the map method for this purpose:

x = [1,2,3,4]
y = x.map { |e| e**2} #=> y=[1,4,9,16]

As you can see, each element of the x array was picked up, squared, and pushed into a new array, which can be referenced using variable named y.

Selecting elements of an array

One can select elements specifying certain criteria defined in an associated block. There is a destructive way and a nondestructive way to accomplish this.

The nondestructive way

An example of the nondestructive way is as follows:

x = [1,2,3,4,5]
x.select { |i| i > 2 } #=> [3,4,5]
x.reject { |i| i < 3 } #=> [3,4,5]
x.drop_while { |i| i < 3 } #=> [3,4,5]
x #=> [1,2,3,4,5]
The destructive way

An example of the destructive way is as follows:

x.select! { |i| i > 2 } #=> [3,4,5]
x.reject! { |i| i < 3 } #=> [3,4,5]

As you can see, in the nondestructive way, the methods returned an array after performing the operations; however, our original array that is x remained unaffected. However, in the destructive way, the original array itself was modified. We'll see a bit more about this in our next section.

主站蜘蛛池模板: 启东市| 四平市| 鸡东县| 洪雅县| 峨眉山市| 武陟县| 金平| 广东省| 台州市| 江北区| 定襄县| 奉节县| 清新县| 寻甸| 宿松县| 乡城县| 扎兰屯市| 高密市| 两当县| 卢龙县| 建湖县| 烟台市| 九寨沟县| 莎车县| 左权县| 莆田市| 团风县| 石柱| 容城县| 巴楚县| 报价| 新竹市| 元氏县| 桃园市| 施秉县| 惠水县| 婺源县| 汾阳市| 玛曲县| 吉安市| 京山县|