Ruby 数组类each_index()操作
Array#each_index() : each_index()是Array类的一个方法,通过对self中的每个_index元素按照给定块的条件操作一次来返回数组元素的索引。
语法。 Array.each_index()
参数:block – 要跟随的条件
返回:条件之后的数组元素的索引
代码 #1 : each_index()方法的例子
# Ruby code for each_index() method
# declaring array
a = ["abc", "nil", "dog"]
# declaring array
b = ["hello", "hi", "dog"]
# each_index
puts "each_index : #{a.each_index {|x| print x, " -- "}}\n\n"
输出:
0 -- 1 -- 2 -- each_index : ["abc", "nil", "dog"]
代码 #2 : each_index()方法的例子
# Ruby code for each_index() method
# declaring array
a = ["abc", "nil", "dog"]
# declaring array
b = ["hello", "hi", "dog"]
# each_index
puts "each_index : #{b.each_index{|x| x = 2}}\n\n"
```
输出:
```ruby
each_index : ["hello", "hi", "dog"]