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

标签 ruby

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

我想做这样的事情

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/

相关文章:

ruby-on-rails - Ruby on Rails 从 'Errno::ENOENT' 中解救出来

ruby - 重新安装 Ruby 以使用 libyaml

ruby-on-rails - Rails 4.1 - 为什么选择 Spring?

javascript - 在 Ruby (Rails) 中评估 module.exports

ruby-on-rails - 动态显示 Controller > Action 作为标题

ruby-on-rails - 捆绑安装:G​​em::RemoteFetcher::FetchError: SSL:...证书验证失败

Ruby Shoes 不适用于符号

ruby - 无效的 gem 格式

ruby-on-rails - Rails 急切加载,可能的错误

ruby - 在 ruby​​ 中运行脚本时等待击键