gpt4 book ai didi

ruby 将内循环值返回给外循环

转载 作者:数据小太阳 更新时间:2023-10-29 07:58:47 26 4
gpt4 key购买 nike

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

最佳答案

可以使用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

关于ruby 将内循环值返回给外循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40656829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com