📜  红宝石 |可枚举的 collect()函数

📅  最后修改于: 2022-05-13 01:55:05.891000             🧑  作者: Mango

红宝石 |可枚举的 collect()函数

enumerablecollect()是 Ruby 中的一个内置方法,它返回一个新数组,其中包含对 enum 中的每个元素运行一次块的结果。每次对每个枚举都重复该对象。如果没有给出对象,它会为每个枚举返回 nil。

示例 1

# Ruby program for collect? method in Enumerable
  
# returns enumerator
enu1 = (2..6).collect {|x| x * 10}

输出

[20, 30, 40, 50, 60]

示例 2

# Ruby program for collect? method in Enumerable
  
  
# returns an enumerator with nil
enu1 = (2..6).collect {}

输出

[nil, nil, nil, nil, nil]