红宝石 |可枚举的 flat_map函数
enumerable的flat_map()是 Ruby 中的一个内置方法,它返回一个新数组,其中包含对 enum 中的每个元素运行一次块的串联结果。如果没有给出块,则返回一个枚举器。
Syntax: block.flat_map { |obj| block }
Parameters: The function takes the block according to which the every block is to be returned. If no block is given, an enumerator is returned.
Return Value: It returns a new array.
示例 1 :
# Ruby program for flat_map method in Enumerable
# Initialize
enu = [12, 18]
# returns enumerator
res = enu.flat_map { |el| [2*el, 3*el] }
输出:
[24, 36, 36, 54]
示例 2 :
# Ruby program for flat_map method in Enumerable
# Initialize
enu = [[17, 21], [19, 100]]
# returns enumerator
res = enu.flat_map { |el| el + [1000] }
输出:
[17, 21, 1000, 19, 100, 1000]