ruby return inner loop value to outer loop -
how return value inner loop .map of 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 |letter_number| numbers.each |number| letter_number.number = letter_number.number + number end end end
i want do_stuff
method return array of updated letternumber
objects. want inner loop return letter_number object on each of iterations outer loop. possible sort of iterator instead of breaking loops out separate methods or something?
you can use inject
method calculate 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 |letter_number| letter.number += numbers.inject(:+) letter_number end end
or use each_with_object
return letter_number after loop.
def do_stuff letter_numbers = // array of letternumber objects numbers = [1, 2, 3] letter_numbers.map |letter_number| numbers.each_with_object(letter_number) |number| letter_number.number = letter_number.number + number end end end
Comments
Post a Comment