gpt4 book ai didi

ruby - 在 Ruby 代码块中获取值而不是最后一条语句

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:05 25 4
gpt4 key购买 nike

<分区>

我想从 Ruby 代码块中的 yield 返回一个值。换句话说,我想将一个值从 block 内部传递到 block 本身。

def bar
puts "in block"
foo = 1
# The next line is wrong,
# but this is just to show that I want to assign a value to foo
foo = yield(foo)
puts "done block #{foo}"
end

puts "start"
bar do |shoop|
puts "doing other stuff"
shoop = 2
puts "doing more stuff"
# The following commented-out line would work,
# but I would rather not force the programmer
# to always put a variable at the end
#shoop
end
puts "done"

我希望看到的输出是:

start
in block
doing other stuff
doing more stuff
done block 2
done

有没有什么方法可以在不依赖 Ruby block 末尾的隐式返回值的情况下实现这一点?我相信这是可能的,因为我之前在 Sinatra 代码块中看到过这种行为。

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