Reputation: 4847
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?
Upvotes: 3
Views: 443
Reputation: 1953
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)
Upvotes: 1
Reputation: 7326
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
Upvotes: 8