gpt4 book ai didi

ruby - 如何使用枚举器

转载 作者:数据小太阳 更新时间:2023-10-29 06:56:22 27 4
gpt4 key购买 nike

在 Ruby Array Class 文档中,我经常发现:

If no block is given, an enumerator is returned instead.

为什么我不将 block 传递给 #map?我这样做有什么用:

[1,2,3,4].map

而不是做:

[1,2,3,4].map{ |e| e * 10 } # => [10, 20, 30, 40]

谁能给我一个使用这个枚举器的非常实际的例子?

最佳答案

好问题。

如果我们想对创建的枚举器执行多项操作怎么办?我们现在不想处理它,因为这意味着我们可能需要稍后创建另一个?

my_enum = %w[now is the time for all good elves to get to work].map # => #<Enumerator: ["now", "is", "the", "time", "for", "all", "good", "elves", "to", "get", "to", "work"]:map>

my_enum.each(&:upcase) # => ["NOW", "IS", "THE", "TIME", "FOR", "ALL", "GOOD", "ELVES", "TO", "GET", "TO", "WORK"]
my_enum.each(&:capitalize) # => ["Now", "Is", "The", "Time", "For", "All", "Good", "Elves", "To", "Get", "To", "Work"]

关于ruby - 如何使用枚举器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20394909/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com