红宝石 |可枚举的 each_with_object()函数
enumerable的each_with_object()是 Ruby 中的一个内置方法,它对每个对象进行迭代并返回初始对象。如果没有给出块,它返回枚举器。
Syntax: enu.each_with_object(obj) { |obj| block }
Parameters: The function takes the block which is used to initialise the initial object.
Return Value: It returns the enumerator, if no block is given, else it returns the initial object.
示例 1 :
# Ruby program for each_with_object method in Enumerable
# Initialize
enu = [7, 9, 10]
# Prints each with object
enu.each_with_object([]) { |obj, el| el << obj+10 }
输出:
[17, 19, 20]
示例 2 :
# Ruby program for each_with_object method in Enumerable
# Initialize
enu = [7, 9, 10]
# Prints each with object
enu.each_with_object([])
输出:
Enumerator: [7, 9, 10]:each_with_object([])