我不知道怎么用谷歌搜索,但我知道我想要什么.

我想做这样的东西

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(或者执行块中的任何代码).

我不知道它的名字是什么,我也不知道怎么谷歌它.

非常需要你们的帮助,谢谢

推荐答案

我会这样做,并将块存储在一个变量中.

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相关问答推荐

运行跳过的RSpec测试,如果通过则失败

在 Ruby 中,如何从派生类中重写同一方法的不同方法调用基类方法?

定义Struct时如何指定成员的类型?

什么是 '?-mix' 在 Ruby 正则表达式中

在Ruby中将关键字与常规参数混合?

为什么 Range 在下降时不起作用?

无法在 Heroku 教程中使用 Python 启动工头

如何调试/显示使用 RestClient 发送的请求

出于调试目的,如何打印有关 NET:HTTPRequest 的信息?

如何声明 RSpec 中示例之间共享的变量?

YAML 每个缩进多少个空格?

Ruby 和您必须使用 OpenSSL 支持重新编译 Ruby 或更改 Gemfile 中的源代码

Ruby 被空格分割

include_examples和it_behaves_like有什么区别?

从 Ruby 中的 URL 获取文件名的好方法是什么?

无法在 Windows 上安装 Aptana Studio 3.6

如何在Ruby中获取给定月份的天数,占年份?

Mustache Templates 可以做模板扩展吗?

测试变量是否等于两个值之一

如何在 Ruby 中做标准差?