可枚舉的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
相關用法
- Ruby Enumerable take()用法及代碼示例
- Ruby Enumerable none?()用法及代碼示例
- Ruby Enumerable one?用法及代碼示例
- Ruby Enumerable first()用法及代碼示例
- Ruby Enumerable sum()用法及代碼示例
- Ruby Enumerable any?用法及代碼示例
- Ruby Enumerable all?用法及代碼示例
- Ruby Enumerable min()用法及代碼示例
- Ruby Enumerable map()用法及代碼示例
- Ruby Enumerable max()用法及代碼示例
- Ruby Enumerable minmax()用法及代碼示例
- Ruby Enumerable drop()用法及代碼示例
- Ruby Enumerable drop_while()用法及代碼示例
- Ruby Enumerable each_slice()用法及代碼示例
- Ruby Enumerable group_by()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 Ruby | Enumerable each_with_index() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。