gpt4 book ai didi

ruby - 为什么这个 .each block 返回的结果与 .select 不同?

转载 作者:数据小太阳 更新时间:2023-10-29 08:00:04 25 4
gpt4 key购买 nike

来自 CodeQuizzes #6:使用包含字母“a”的所有元素从 captain_planet 数组创建一个新数组。

captain_planet = ["earth", "fire", "wind", "water", "heart"]

我理解他们的回答:

captain_planet.select do |word|
word.include?("a")
end

但是,我似乎无法弄清楚为什么这不会返回相同的东西:

ret = []

captain_planet.each do |x|
if x.include?('a')
ret.push(x)
end
end

想法?

最佳答案

尝试在 block 结束后查看 ret 的输出。

2.0.0p247 :001 > ret = []
=> []
2.0.0p247 :002 > captain_planet = ["earth", "fire", "wind", "water", "heart"]
=> ["earth", "fire", "wind", "water", "heart"]
2.0.0p247 :003 > captain_planet.each do |x|
2.0.0p247 :004 > if x.include?('a')
2.0.0p247 :005?> ret.push(x)
2.0.0p247 :006?> end
2.0.0p247 :007?> end
=> ["earth", "fire", "wind", "water", "heart"]
2.0.0p247 :008 > puts ret
earth
water
heart
=> nil

关于ruby - 为什么这个 .each block 返回的结果与 .select 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21323934/

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