當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。