Ruby has this method called the block_given
in it so that we can check to see if a block is passed and process accordingly if given. Is there an equivalent method in crystal?
Asked
Active
Viewed 406 times
3

coderhs
- 4,357
- 1
- 16
- 25
-
1Possible duplicate of [Crystal How to check if the block argument is given inside the function](https://stackoverflow.com/questions/39190854/crystal-how-to-check-if-the-block-argument-is-given-inside-the-function) – Oleh Prypin Oct 21 '17 at 16:00
2 Answers
8
Crystal does not have it for a moment. But you can have similar behavior using method overloading:
def foo
foo {}
end
def foo
yield
end
foo { }
foo

Vitalii Elenhaupt
- 7,146
- 3
- 27
- 43
1
If you absolutely must know whether a block was given, you can do something like this:
def foo(block : (String ->)? = nil)
if block
block.call("Block given")
else
puts "No block given"
end
end
def foo(&block : String ->)
foo(block)
end
foo { |s| puts s }
foo
(For more information on Proc
syntax, see https://crystal-lang.org/reference/syntax_and_semantics/type_grammar.html#proc)

fn control option
- 1,745
- 6
- 18
-
fn's answer code not run on Crystal 1.6.1 anymore, but the key point is correct. following is working code. https://forum.crystal-lang.org/t/what-is-the-equivalent-of-ruby-block-given/5059/3?u=zw963 – zw963 Nov 02 '22 at 05:52