Reputation: 838
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>"
Upvotes: 3
Views: 796
Reputation: 18804
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!" }
Upvotes: 1
Reputation: 838
Can't do this for blocks, but for procs...
def hello
puts yield
end
my_proc = Proc.new {"I am #{my_proc}"}
method("hello").call(&my_proc)
#I am <#Proc:0x0...@...>
Upvotes: 0