Search code examples
rubyproccrystal-lang

Call optional proc only if proc was set


So I am porting a tool from ruby were a callback block could be defined on an object and I want it to be called in case the callback was set. So basically something like this.

def set_block(&block)
  @new_kid_on_the_block = block
end

def call_the_block_if_it_was_defined
  block.call("step by step") if block = @new_kid_on_the_block
end

I am pretty sure this is an easy task but somehow I just run into problems.

Thank you in advance!


Solution

  • In Crystal you almost always have to specify types of instance variables explicitly. So here is how it could look:

    class A
      alias BlockType = String -> String
    
      def set_block(&block : BlockType)
        @block = block
      end
    
      def call_block
        @block.try &.call("step by step")
      end
    end
    
    a = A.new
    pp a.call_block # => nil
    a.set_block { |a| a + "!" }
    pp a.call_block # => "step by step!"
    

    Take a look at Capturing blocks for more.