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


Ruby Enumerable each_with_index()用法及代碼示例

可枚舉的each_with_index()是Ruby中的一種內置方法,它根據給定的塊對可枚舉中的項目進行哈希處理。如果沒有給出塊,則返回一個枚舉數。

用法: enu.each_with_index { |obj| block }

參數:該函數采用用於初始化各個對象索引的塊。


返回值:如果沒有給出塊,則返回枚舉數,否則將哈希該項目。

例子1

# Ruby program for each_with_index method in Enumerable 
  
# Initialize  
hashing = Hash.new
enu = [7, 9, 10] 
  
  
enu.each_with_index { |item, index| 
  hashing[item] = index 
} 
  
# prints hash 
puts hashing

輸出

{7=>0, 9=>1, 10=>2}

例子2

# Ruby program for each_with_index method in Enumerable 
  
# Initialize  
hashing = Hash.new
enu = [7, 9, 10] 
  
  
enu.each_with_index

輸出

Enumerator: [7, 9, 10]:each_with_index


相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 Ruby | Enumerable each_with_index() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。