gpt4 book ai didi

ruby - [1,2,3].to_enum 和 [1,2,3].enum_for 在 Ruby 中的区别

转载 作者:数据小太阳 更新时间:2023-10-29 07:12:02 25 4
gpt4 key购买 nike

在 Ruby 中,我试图理解 to_enumenum_for 方法。在我提出问题之前,我提供了一些示例代码和两个示例来帮助理解上下文。

示例代码:

# replicates group_by method on Array class
class Array
def group_by2(&input_block)
return self.enum_for(:group_by2) unless block_given?
hash = Hash.new {|h, k| h[k] = [] }
self.each { |e| hash[ input_block.call(e) ] << e }
hash
end
end

示例#1:

irb (main)> puts [1,2,3].group_by2.inspect
=> #<Enumerator: [1, 2, 3]:group_by2>

在示例 #1 中:在数组 [1,2,3] 上调用 group_by,不传入 block ,返回使用命令 生成的枚举器>self.enum_for(:group_by_2).

示例#2

irb (main)> puts [1,2,3].to_enum.inspect
=> #<Enumerator: [1, 2, 3]:each>

在示例 #2 中,枚举数是通过调用数组 [1,2,3] 上的 to_enum 方法生成的

问题:

示例 1 和示例 2 中生成的枚举器是否以任何方式表现不同?我可以从检查的输出中看到它们显示的标签略有不同,但我可以发现枚举器的行为有任何差异。

# Output for example #1
#<Enumerator: [1, 2, 3]:each> # label reads ":each"

# Output for example #2
#<Enumerator: [1, 2, 3]:group_by2> # label reads ":group_by2"

最佳答案

p [1, 2, 3].to_enum
p [1, 2, 3].enum_for

--output:--

#<Enumerator: [1, 2, 3]:each>
#<Enumerator: [1, 2, 3]:each>

来自文档:

to_enum

Creates a new Enumerator which will enumerate by calling method on obj, passing args if any.

...

enum_for

Creates a new Enumerator which will enumerate by calling method on obj, passing args if any.

ruby 是一种通常具有同义词方法名称的语言。

后续问题:

Does the symbol in the command [1,2,3].to_enum(:foo) serve a purpose, other than replacing :each with :foo in the output?

是的。默认情况下,ruby 将枚举器连接到接收器的 each() 方法。有些类没有 each() 方法,例如 String:

str = "hello\world"
e = str.to_enum
puts e.next

--output:--
1.rb:3:in `next': undefined method `each' for "helloworld":String (NoMethodError)
from 1.rb:3:in `<main>

to_enum() 允许您指定希望枚举器使用的方法:

str = "hello\nworld"
e = str.to_enum(:each_line)
puts e.next

--output:--
hello

现在,假设您有数组 [1, 2, 3],并且您想要为您的数组创建一个枚举器。数组有一个 each() 方法,但不是用 each() 创建一个枚举器,它将返回数组中的每个元素,然后结束;你想创建一个枚举器,一旦它到达末尾就从数组的开头重新开始?

e = [1, 2, 3].to_enum(:cycle)

10.times do
puts e.next()
end

--output:--
1
2
3
1
2
3
1
2
3
1

关于ruby - [1,2,3].to_enum 和 [1,2,3].enum_for 在 Ruby 中的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23850422/

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