如何将内部循环中的值返回到外循环的.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对象返回到外部循环。是否可以使用某种迭代器而不是将循环分解为单独的方法或什么?
答案 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