I am wondering how to get the name of a block/proc while in the block that will then be passed to a method. I need the name of a block like so:
method("hello") do
puts "My name is #{self}"
end
Which would print out something like when the method runs the block:
"My name is #<Proc:0xa3de668@/path/to/file.rb:8>"
You can get a reference to the implicitly passed block inside the method yield-ing it, by calling Proc.new (inside the method) without supplying a block. For instance:
def speak
puts yield
block = Proc.new # Creates a proc object from the implictly passed block.
puts block.call
end
speak { "Hello, from implicit block!" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With