从codequizzes 6:从captain planet数组创建一个包含字母“a”的所有元素的新数组。
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
思想?
最佳答案
尝试在块结束后查看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块不返回与.select相同的内容?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21323934/