I have a block which I need to pass to File.open and another method XXobject#read. Since I passed the same block to those two methods, I would like to find a way to avoid duplicating the code of block.
I tried to define a Proc object, but File.open seems not to accept a Proc object. I am wondering why. As far as I know, a block is stored as a Proc object.
Is there a way to avoid duplicated blocks in Ruby?
You need to convert Proc to Block:
blk = Proc.new{puts 1234567890}
def a; yield; end
a(&blk)
1.9.3-194 (main):0 > a(&blk)
1234567890
=> nil
As already written in comment, you can convert proc to block using &.
Once you've defined your_proc, you can pass it as a block argument using &your_proc
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