gpt4 book ai didi

arrays - 为什么 each_cons 产生数组而不是多个值?

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:09 24 4
gpt4 key购买 nike

我只想对数组中的连续元素应用二元运算,例如:

[1, 2, 3, 4].each_cons(2).map { |a, b| a.quo(b) }
#=> [(1/2), (2/3), (3/4)]

这是一个人为的例子,操作并不重要。

我很惊讶,我不能只写:

[1, 2, 3, 4].each_cons(2).map(&:quo)
#=> NoMethodError: undefined method `quo' for [1, 2]:Array

这是因为 each_cons 不产生多个值,而是一个包含这些值的数组。

它是这样工作的:

def each_cons_arrays
return enum_for(__method__) unless block_given?
yield [1, 2]
yield [2, 3]
yield [3, 4]
end

each_cons_arrays.map(&:quo)
#=> NoMethodError: undefined method `quo' for [1, 2]:Array

我希望:

def each_cons_values
return enum_for(__method__) unless block_given?
yield 1, 2
yield 2, 3
yield 3, 4
end

each_cons_values.map(&:quo)
#=> [(1/2), (2/3), (3/4)]

这背后的原理是什么?为什么总是有一个数组会更好?

顺便说一下,另一方面,with_index 确实会产生多个值:

[1, 1, 1].each.with_index(2).map(&:quo)
#=> [(1/2), (1/3), (1/4)]

最佳答案

根据我的经验,将 ruby​​ 中的多个值视为数组会有所帮助。

它认为它是

[1,2,3].each_cons(2) do |iter|
a,b = iter
do_stuff(a,b)
end

如果你想这样做,我会将 quo 方法添加到自定义类中,然后执行

class Foobar
def initialize(a,b)
@a = a
@b = b
end

def quo
do_stuff
end
end

[1,2,3]
.each_cons(2)
.map { |a,b| Foobar.new(a,b) }
.map(:quo)

这对您的用例有用吗?

关于arrays - 为什么 each_cons 产生数组而不是多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37673086/

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