Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to avoid duplicated blocks in Ruby?

Tags:

ruby

block

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?

like image 484
Kurt Liu Avatar asked Dec 03 '25 13:12

Kurt Liu


2 Answers

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
like image 114
sumskyi Avatar answered Dec 06 '25 08:12

sumskyi


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

like image 29
apneadiving Avatar answered Dec 06 '25 09:12

apneadiving



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!