gpt4 book ai didi

ruby - 将两个添加到数组中的元素并显示总和

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:16 24 4
gpt4 key购买 nike

我编写了一个方法,它应该执行以下操作。以数组作为输入,并将数组的数字加 2。

所以基本上:

array = [1,2,3]
new_array = array.map! { |item| item + 2 }

但是我想显示总和。所以对于数组,它应该说“1 + 2 = 3”,“2 + 2 = 4 等......”而不是仅仅 3。我试过这个:

a = [1,2,3]

def add_two(a)

a.map {|item| puts "#{item} + 2 = item + 2"}
a.map!(&:to_s)
end

add_two(a)

但是我没弄对。有没有想过我该如何解决这个问题?

最佳答案

使用:

array = [1,2,3]
# if you don't want to change the original array, then don't use map!
new_array = array.map { |item| "#{item} + 2 = #{item + 2}" }

# or write in a function.
def add_two(a)
a.map { |item| "#{item} + 2 = #{item + 2}" }
end

关于ruby - 将两个添加到数组中的元素并显示总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27617928/

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