Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of Block while in Block (self) Ruby

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>"
like image 799
slyv Avatar asked Jan 23 '26 02:01

slyv


1 Answers

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!" }
like image 142
Jikku Jose Avatar answered Jan 25 '26 18:01

Jikku Jose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!