Searching for combinations of words and numbers My model called Customer contains a method called generate_fields which creates records based on its return values.

def generate_fields
  words.map do |word|
    numbers.map do |number|
      content = find_content(word, number)
      next if content.nil?

      {
        kind: word,
        value: content
      }
    end.compact
  end.flatten
end

#[
#  { kind: "S", value: "BRL" },
#  { kind: "M", value: "AUS" },
#  { kind: "L", value: "PER" },
#]


The methods words and numbers are private and return an array of strings. Their implementation is not relevant to this discussion. generate_fields returns an array of hashes which is used to create multiple customers at the database.

Customer.create(generate_fields)


The problem is compact and flatten create a new array for every time they are called as pointed out by @David Aldridge. How can this function be rewritten to avoid excessive array creation? Thanks in advance.
I'm not a fan of the latter because the compact and flatten methods create new arrays.

Here's another variation with two additional style options: use of product to combine the two arrays, and each_with_object:

def generate_fields_3
  words   = ["foo", "bar", "bla"]
  numbers = [1, 2, 3]

  words.product(numbers).each_with_object([]) do |(word, number), fields|
    content = find_content(word, number)
    next if content.nil?

    fields &lt;&lt; {
      kind: word,
      value: content
    }
  end
end