我一直对Enumerable#all?
和Enumerable#each
的用例感到困惑。例如
['.txt', '-hello.txt'].all? do |suffix|
puts "temp#{suffix}"
end
适合我,也适用
['.txt', '-hello.txt'].each do |suffix|
puts "temp#{suffix}"
end
也适合我。
我应该选择.all?
或.each
?
答案 0 :(得分:5)
all?
评估传递给它的块,如果所有元素都满足,则返回true
,否则返回false
。
each
是一种使用块迭代可枚举对象的方法。它将评估每个对象的块。在您的情况下,您想使用each
。
答案 1 :(得分:1)
查看您的代码和输出:
['.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
的说明:强> 的
将集合的每个元素传递给给定的块。如果块永远不会返回 false或nil ,则该方法返回 true 。
您的第一个代码puts
在将第一个元素传递给块后返回nil
。传递给all?
的阻止只有在每个项目评估为true
时才会继续。因此块返回"temp.txt"
。在第二个版本中不是这种情况。由于p
永远不会返回nil
。因此,块的评估结果为true
,因为除了true
和nil
之外,所有对象都是false
。