Enumerable#all的正确用例是什么?和可枚举#在Ruby中?

时间:2013-04-10 07:12:58

标签: ruby enumerable

我一直对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

2 个答案:

答案 0 :(得分:5)

all?评估传递给它的块,如果所有元素都满足,则返回true,否则返回false

each是一种使用块迭代可枚举对象的方法。它将评估每个对象的块。在您的情况下,您想使用each

请参阅所有文件 here每个 here的文档。

答案 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

说明:

Enum#all?说:

  

将集合的每个元素传递给给定的块。如果块永远不会返回 false或nil ,则该方法返回 true

您的第一个代码puts在将第一个元素传递给块后返回nil。传递给all?的阻止只有在每个项目评估为true时才会继续。因此块返回"temp.txt"。在第二个版本中不是这种情况。由于p永远不会返回nil。因此,块的评估结果为true,因为除了truenil之外,所有对象都是false