gpt4 book ai didi

ruby - 如何生成一个 proc 以返回哈希中的连续条目,已转换?

转载 作者:数据小太阳 更新时间:2023-10-29 08:30:30 24 4
gpt4 key购买 nike

我想生成一个过程,在调用时返回任何 Enumerable 的连续值。换句话说:

a_proc = generate_proc([:a, :b, :c])
a_proc.call # => :a
a_proc.call # => :b

等等

理想情况下,我也想在返回之前翻译它,这样它可能会像这样被使用:

a_proc = generate_proc([:a, :b, :c ]) { |e| "Element: #{e.inspect}" }
a_proc.call # => "Element: :a"
a_proc.call # => "Element: :b"
a_proc.call # => "Element: :c"

最佳答案

这不是你想要的,但我认为它可能满足你的需求:

an_enum = [:a, :b, :c].each

an_enum.next # => :a
an_enum.next # => :b

和:

an_enum = [:a, :b, :c].map { |e| "Element: #{e.inspect}" }.each
# or, if you want to defer calling the block...
an_enum = [:a, :b, :c].lazy.map { |e| "Element: #{e.inspect}" }

an_enum.next # => "Element: :a"
an_enum.next # => "Element: :b"
an_enum.next # => "Element: :c"

有关更多信息,请查看 EnumeratorEnumerator::Lazy .

future 的更新,更聪明,更帅的我:

要回答您原来的问题,您可以使用 Object#method 将任何对象的方法变成一个绑定(bind)的、可调用的对象。我们甚至可以对 Enumerator#next 执行此操作!

an_enum = [:a, :b, :c].each
a_proc = an_enum.method(:next)

a_proc.call # => :a
a_proc.call # => :b
a_proc.call # => :c

关于ruby - 如何生成一个 proc 以返回哈希中的连续条目,已转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39299899/

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