1

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?

5 Answers 5

8
barcodes = Array.new(count){ Barcode.create }
Sign up to request clarification or add additional context in comments.

1 Comment

Several good answers but this is the best. I can even drop the variable at this point so very concise
8

Try to the following:

count.times.map { Barcode.create }

Hope it helps!

Comments

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

Comments

1

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

Comments

1

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

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

1 Comment

Haha I definitely wouldn't use it but it's very interesting! thanks for the suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.