Andrew
Andrew

Reputation: 1013

Can I add object to an array in a loop and then return the array in the same line?

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

Answers (5)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Just out of curiosity, lazy instantiation of any amount of the Barcodes:

[->() { Barcode.create }].cycle.take(count).map(&:call)

Upvotes: 1

radoAngelov
radoAngelov

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

steenslag
steenslag

Reputation: 80065

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

Upvotes: 8

fongfan999
fongfan999

Reputation: 2624

Try to the following:

count.times.map { Barcode.create }

Hope it helps!

Upvotes: 8

Vijay Dev
Vijay Dev

Reputation: 27466

def create_barcodes(count)
  barcodes = (1..count).map { Barcode.create }
end

Upvotes: 2

Related Questions