作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不知道如何用谷歌搜索它,但我知道我想要什么。
我想做这样的事情
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/
我是一名优秀的程序员,十分优秀!