abdul ahmad abdul ahmad - 19 days ago 5
Ruby Question

ruby return inner loop value to outer loop

how do I return the value from an inner loop to the .map of an outer loop, example:

class LetterNumber
def initialize(letter, number)
@letter = letter
@number = number
end
end

do_stuff
letter_numbers = // array of LetterNumber objects
numbers = [1, 2, 3]

letter_numbers.map do |letter_number|
numbers.each do |number|
letter_number.number = letter_number.number + number
end
end
end


I want the
do_stuff
method to return an array of the updated
LetterNumber
objects. so I want the inner loop to return a letter_number object on each of its iterations to the outer loop. Is this possible with some sort of iterator instead of breaking the loops out into separate methods or something?

Answer

You can use inject method to calculate the sum directly:

class LetterNumber
  def initialize(letter, number)
    @letter = letter
    @number = number
  end
end

def do_stuff
  letter_numbers = // array of LetterNumber objects
  numbers = [1, 2, 3]

  letter_numbers.map do |letter_number|
    letter.number += numbers.inject(:+)
    letter_number
  end
end

or use each_with_object to return letter_number after your loop.

def do_stuff
  letter_numbers = // array of LetterNumber objects
  numbers = [1, 2, 3]

  letter_numbers.map do |letter_number|
    numbers.each_with_object(letter_number) do |number|
      letter_number.number = letter_number.number + number
    end
  end
end
Comments