ruby .each
Ruby Array.each方法 (Ruby Array.each method)
Array.each method can be easily termed as a method which helps you to iterate over the Array. This method first processes the first element then goes on the second and the process keeps on going on until the last element is not processed. This method is very important when it comes to carrying out the process of traversing the array. This method works in the way that each element of the instance of Array class is yielded to the block supplied to the method. The task is completed in a particular sequence. You will need to provide a temporary variable inside the pair of the disjoint symbol because you will be able to fetch the element with the help of that variable only. This simply means that first the value of an element is temporarily stored in that variable and it is stored ever since the next element does not come into the scene.
Array.each方法可以轻松地称为可帮助您遍历Array的方法 。 此方法首先处理第一个元素,然后继续处理第二个元素,然后继续进行直到没有处理最后一个元素。 在执行遍历数组的过程时,此方法非常重要。 该方法的工作方式是将Array类实例的每个元素都屈服到提供给该方法的块中。 该任务按特定顺序完成。 您将需要在不相交符号对中提供一个临时变量,因为您将只能在该变量的帮助下获取元素。 这仅意味着首先将元素的值临时存储在该变量中,并且由于下一个元素不进入场景就将其存储。
This operation or process does not bring any change in the actual values of Array elements.
此操作或过程不会使Array元素的实际值发生任何变化。
Syntax:
句法:
Array.each { |var| #statements}
Parameter(s):
参数:
This method does not invite any type of argument.
此方法不邀请任何类型的参数。
Example 1:
范例1:
=begin
Ruby program to demonstrate Array.each
=end
# array declaration
Adc = ['Ruby','Includehelp.com','Ruby','C++','C#']
# counter intialization
cnt = 1
# Array.each method
Adc.each{ |ele|
puts "#{cnt} element is #{ele}"
cnt = cnt + 1
}
Output
输出量
1 element is Ruby
2 element is Includehelp.com
3 element is Ruby
4 element is C++
5 element is C#
The above code can be modified as,
上面的代码可以修改为
Example 2:
范例2:
=begin
Ruby program to demonstrate Array.each
=end
# array declaration
Adc = ['Ruby','Includehelp.com','Ruby','C++','C#']
# counter initialization
cnt = 1
Adc.each do |ele|
puts "#{cnt} element is #{ele}"
cnt = cnt + 1
end
Output
输出量
1 element is Ruby
2 element is Includehelp.com
3 element is Ruby
4 element is C++
5 element is C#
Explanation:
说明:
In the above two program codes, you can observe that the method named Array.each can be used in two different ways. Both the ways are quite understandable and their use depends upon your comfort. It is very clear with the help of output that the processing of Array elements starts from index 0 and finishes when the last element is being processed. You can never bring any change in the elements of Array with the help of this method because this method is one of the examples of non-destructive methods.
在以上两个程序代码中,您可以观察到名为Array.each的方法可以以两种不同的方式使用。 两种方式都是可以理解的,它们的使用取决于您的舒适度。 在输出的帮助下,很明显Array元素的处理从索引0开始,并在处理最后一个元素时结束。 借助于此方法,您永远无法对Array的元素进行任何更改,因为该方法是非破坏性方法的示例之一。
翻译自: https://www.includehelp.com/ruby/array-each-method-with-example.aspx
ruby .each