dax
dax

Reputation: 10997

A more concise way to create an array, fill it, then return it?

I have a method to scan items:

def scan(*items)
  scanned_items = []
  items.each { |item| scanned_items << item }
  scanned_items
end

I see (and use) the guts of this method often - that is, make an empty array, put some stuff in it, and then return the array. Is there a more concise way to write this?

Upvotes: 0

Views: 50

Answers (2)

spickermann
spickermann

Reputation: 106882

If there is nothing to do:

items.dup

for simple stuff:

items.map(&:simple)

really complex operations:

[].tap do |result|
  items.each do |item|
    # complex conditions, loops, etc
    result << item
  end
end

Upvotes: 3

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

This concrete example can be simplified to this

scanned_items = items.dup

Upvotes: 4

Related Questions