红宝石 |可枚举的 each_with_index()函数
enumerable的each_with_index()是 Ruby 中的一个内置方法,根据给定的块对 enumerable 中的项目进行哈希处理。如果没有给出块,则返回一个枚举器。
Syntax: enu.each_with_index { |obj| block }
Parameters: The function takes the block which is used to initialise the index to the individual objects.
Return Value: It returns the enumerator, if no block is given, else it hashes the items.
示例 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