红宝石 |数组类 each_index() 操作
Array#each_index() : each_index()是一个 Array 类方法,它通过对 self 中的 each_index 元素执行一次给定块中的条件来返回数组元素的索引。
Syntax: Array.each_index()
Parameter: block - condition to follow
Return: index of the array element following the condition
代码 #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"
输出 :
each_index : ["hello", "hi", "dog"]