ruby将内部循环值返回到外部循环

时间:2016-11-17 13:58:38

标签: ruby loops

如何将内部循环中的值返回到外循环的.map,例如:

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

我希望do_stuff方法返回更新的LetterNumber对象的数组。所以我希望内部循环在每次迭代时将letter_number对象返回到外部循环。是否可以使用某种迭代器而不是将循环分解为单独的方法或什么?

1 个答案:

答案 0 :(得分:3)

您可以使用inject方法直接计算总和:

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

或使用each_with_object在循环后返回letter_number。

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