Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 我可以将对象添加到循环中的数组中,然后在同一行中返回该数组吗?_Arrays_Ruby - Fatal编程技术网

Arrays 我可以将对象添加到循环中的数组中,然后在同一行中返回该数组吗?

Arrays 我可以将对象添加到循环中的数组中,然后在同一行中返回该数组吗?,arrays,ruby,Arrays,Ruby,我有一些简单的ruby代码,其中我创建了一个数组,创建了一堆对象,并将它们放入数组中,然后返回数组 def create_barcodes(count) barcodes = Array.new count.times { barcodes.push(Barcode.create) } barcodes end 感觉应该有一种方法将其减少到一行或两行,并且至少避免必须在末尾引用条形码数组才能返回。有什么聪明的方法可以让计数循环返回数组吗?尝试以下方法: def create_bar

我有一些简单的ruby代码,其中我创建了一个数组,创建了一堆对象,并将它们放入数组中,然后返回数组

def create_barcodes(count)
  barcodes = Array.new
  count.times { barcodes.push(Barcode.create) }
  barcodes
end
感觉应该有一种方法将其减少到一行或两行,并且至少避免必须在末尾引用条形码数组才能返回。有什么聪明的方法可以让计数循环返回数组吗?

尝试以下方法:

def create_barcodes(count)
  barcodes = (1..count).map { Barcode.create }
end
count.times.map { Barcode.create }
希望有帮助

尝试以下操作:

count.times.map { Barcode.create }
barcodes = Array.new(count){ Barcode.create }

希望有帮助

在当前示例中,您不需要实例化新数组-只需使用映射即可

barcodes = Array.new(count){ Barcode.create }
另外,如果您发现自己处于必须实例化新数组的情况下,请用数据填充它,然后返回它,我建议使用tap

在您的情况下,代码如下所示:

Array.new.tap do |barcodes|
  count.times { barcodes.push(Barcode.create) }
end

在当前的示例中,您不需要实例化一个新数组,只需使用映射即可

另外,如果您发现自己处于必须实例化新数组的情况下,请用数据填充它,然后返回它,我建议使用tap

在您的情况下,代码如下所示:

Array.new.tap do |barcodes|
  count.times { barcodes.push(Barcode.create) }
end

只是出于好奇,任意数量条形码的惰性实例化:


只是出于好奇,任意数量条形码的惰性实例化:


有几个好答案,但这是最好的。我甚至可以在这一点上删除变量,因此非常简洁地给出几个好的答案,但这是最好的。我甚至可以在这一点上删除变量,所以非常简洁。哈哈,我肯定不会使用它,但它非常有趣!谢谢你的建议。哈哈,我肯定不会用它,但它很有趣!谢谢你的建议。