当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Array class each_index()用法及代码示例


Array#each_index():each_index()是一种Array类方法,通过对自身中的each_index元素遵循给定块中的条件,一次返回数组元素的索引。

用法: Array.each_index()

参数:  block - condition to follow

返回: 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"]


相关用法


注:本文由纯净天空筛选整理自mayank5326大神的英文原创作品 Ruby | Array class each_index() operation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。