6.26. Ruby iterator

发布时间 :2023-10-30 23:00:07 UTC      

To put it simply: iterate means doing the same thing over and over again, sothe iterator is used to repeat the same thing many times.

Iterators are methods supported by collections. The object that stores a setof data members is called a collection. In Ruby, arrays (Array) and hashes can be called sets.

The iterator returns all the elements of the collection, one by one. Here wewill discuss two kinds of iterators each and collect .

6.26.1. Ruby each iterator #

The each iterator returns all the elements of the array or hash.

Grammar #

collection.eachdo\|variable\|codeend

Execute for each element in the collection code . In this case, the collection can be an array or a hash.

Example #

#!/usr/bin/rubyary=[1,2,3,4,5]ary.eachdo\|i\|putsiend

The output of the above instance is as follows:

1
2
3
4
5

each iterator is always associated with a block. It returns each value of the array to the block, one by one. Values are stored in variables``i`` and then displayed on the screen.

6.26.2. Ruby collect iterator #

The collect iterator returns all elements of the collection.

Grammar #

collection=collection.collect

collect method does not always need to be associated with a block. collect method returns the entire collection, whether it is an array or a hash.

6.26.3. Example #

Example #

#!/usr/bin/rubya=[1,2,3,4,5]b=Array.newb=a.collect{ \|x\|x}putsb

The output of the above instance is as follows:

1
2
3
4
5

Note: collect method is not the correct way to copy between arrays. Here’s another one called clone method for copying one array to another

When you want to do something on each value to get a new array, you usually use the collect method. For example, the following code generates an array whose value is 10 times that of each value.

Example #

#!/usr/bin/rubya=[1,2,3,4,5]b=a.collect{\|x\|10*x}putsb

The output of the above instance is as follows:

10
20
30
40
50

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.