从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
思想?
答案 0 :(得分:3)
尝试在块结束后查看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