查看您的代码和输出:
['.txt', '-hello.txt'].all? do |suffix|
puts "temp#{suffix}"
end
p "======================="
['.txt', '-hello.txt'].each do |suffix|
puts "temp#{suffix}"
end
输出:
temp.txt
"======================="
temp.txt
temp-hello.txt
但现在的问题是为什么第一个代码中的“temp.txt”?. 是的,作为puts回报nil。现在见下图:
['.txt', '-hello.txt'].all? do |suffix|
p "temp#{suffix}"
end
p "======================="
['.txt', '-hello.txt'].each do |suffix|
puts "temp#{suffix}"
end
输出:
"temp.txt"
"temp-hello.txt"
"======================="
temp.txt
temp-hello.txt
解释:
Enum#all?说:
将集合的每个元素传递给给定的块。如果块从不返回false 或 nil ,则该方法返回true。
您的第一个代码在将第一个元素传递给块后puts返回。nil仅当每个项目评估为 时,传递给的块all?才会继续true。因此块返回"temp.txt"。在第二个版本中不是这种情况。因为p永远不会回来nil。因此该块的计算结果为true,因为所有对象都是true除nil和false。