The Crystal Programming Language Forum

Call a block of code?

Is there anyway to call a block of code to be reused again later in a script? Or make it so a user is able to input a command and trigger that block of code?
I’m making a terminal based script, that keeps track of certain scores and values, and want the user to be able to call on the code blocks that are detailing what each score can be used for, or is describing…

Probably are looking for a Proc. That combined with Option Parser might be what you’re looking for? Can also use normal classes/methods with the option parser.

Proc worked perfectly, was exactly what I needed thanks. Had seen it in the docs, but couldn’t understand how to get it to work, or what it was for. Finally was able to XD

1 Like

Just so you know, blocks can be captured and reused. Take this code as an example:

callbacks = [] of Proc(String, Bool)

def add_callback(&block : String -> Bool)
  callbacks << block
end

add_callback do |string|
  string == "Hello world"
end

callbacks.each do |cb|
  cb.call("Hello world) # => true
end

Blocks are really just Procs, so they can be passed around in the same way. I did a lot of that here and here.