gpt4 book ai didi

ruby - 如何在 Ruby 中创建可调用属性

转载 作者:行者123 更新时间:2023-12-05 09:01:10 26 4
gpt4 key购买 nike

我不知道如何用谷歌搜索它,但我知道我想要什么。

我想做这样的事情

class SchedulingManager
attr_accessor :on_start

def call
on_start
end
end

scheduling = SchedulingManager.new
scheduling.on_start do
puts "hello"
end

所以我希望我的 on_start 在这里通过 do block 样式启动。并保存它,以便我可以调用方法 call 并打印 hello(或执行代码块中的任何代码)。

我不知道它的名字,我也不知道如何谷歌它。

请大家帮忙,谢谢

最佳答案

我会这样做并将 block 存储在变量中。

class SchedulingManager
def on_start(&block)
@block = block
end

def call
@block&.call
end
end

scheduling = SchedulingManager.new
scheduling.on_start do
puts "hello"
end

scheduling.call
#=> hello

关于ruby - 如何在 Ruby 中创建可调用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74052090/

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