What is the equivalent of Ruby block_given?

How to convert following Ruby code into Crystal? (with basically same method signature)

def foo(sock_path, &block)
  if block
      block.call(100)
  end
end

Thanks.

1 Like

Crystal How to check if the block argument is given inside the function - Stack Overflow has some interesting discussion…

1 Like

Oops, i quickly checked same SO author another answer before. but that code not work, i link that answer back here.

Following code work well on Crystal 1.6.1

# (1)
def foo(sock_path, &block : Int32 -> Nil)
  puts "11111"
  foo(sock_path, block)
end

# (2)
def foo(sock_path, block : Proc(Int32, Nil)? = nil)
  puts "22222"
  if block
    block.call(100)
  end
end

# both works

foo "some/path", ->(x : Int32) { puts x }

foo "some/path" do |x|
  puts x
end

# The interest things is: this actually invoke above (2)
foo("some/path")


Thanks

3 Likes