Reputation: 1013
I have some simple ruby code where I create an Array, create a bunch of objects and push them into the array and then return the array
def create_barcodes(count)
barcodes = Array.new
count.times { barcodes.push(Barcode.create) }
barcodes
end
It feels like there should be a way to reduce this to one or two lines and at a minimum avoid having to reference the barcodes
array at the end so it gets returned. Is there some clever way to get the count loop to return the array?
Upvotes: 1
Views: 161
Reputation: 121000
Just out of curiosity, lazy instantiation of any amount of the Barcodes
:
[->() { Barcode.create }].cycle.take(count).map(&:call)
Upvotes: 1
Reputation: 714
In the current example you don't need to instantiate a new array - just use the map
method.
Also if you find yourself in a situation that you have to instantiate a new array, fill it up with data and then return it I would suggest using the tap
method.
In your case the code would look like:
Array.new.tap do |barcodes|
count.times { barcodes.push(Barcode.create) }
end
Upvotes: 1
Reputation: 2624
Try to the following:
count.times.map { Barcode.create }
Hope it helps!
Upvotes: 8
Reputation: 27466
def create_barcodes(count)
barcodes = (1..count).map { Barcode.create }
end
Upvotes: 2