Kyrylo Silin

Full-stack developer at Airbrake.io. Core team Pry. Passionate about open source, debuggers and food.

Blocks in Ruby are always there

You probably know that even if your method doesn’t accept blocks, you still can pass them.

def hello(hi)
  puts hi
end

hello('hi') { puts "I'm useless" }
#=> hi

What happens to that block? Well, even though you can’t block.call the block being passed, it is still accessible. For the sake of clearer demonstration I use the method_source gem.

# The `Proc#source` method is powered by method_source.

$block = proc { puts "hi!" }

class Hello
  def hello
    binding
  end
end

bindval = Hello.new.hello(&$block) #=> #<Binding:0x007fa2b2953d58>
bindval.eval("Proc.new").source #=> "$block = proc { puts \"hi!\" }\n"