coderhs
coderhs

Reputation: 4847

equivalent of ruby `block_given?` in crystal

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

Answers (2)

fn control option
fn control option

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

Vitalii Elenhaupt
Vitalii Elenhaupt

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

Related Questions