Home > Software engineering >  How to make callable attribute in Ruby
How to make callable attribute in Ruby

Time:10-14

I do not know how to google it, but i know what i want.

i want to make something like this

class SchedulingManager
  attr_accessor :on_start

  def call
    on_start
  end
end

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

so i want my on_start here to be initiate by do block style. and save it so i can call in method call and print hello (or do whatever code in the block).

i do not know what the name of it, i also do not know how to google it.

Kindly need your help guys, thanks

CodePudding user response:

I would do it like this and store the block in a variable.

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
  •  Tags:  
  • ruby
  • Related