Kurt Liu
Kurt Liu

Reputation: 630

Is there a way to avoid duplicated blocks in Ruby?

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?

Upvotes: 3

Views: 136

Answers (3)

chucai
chucai

Reputation: 21

proc = Proc.new &proc it is block, block could used as a args for methods

Upvotes: 0

apneadiving
apneadiving

Reputation: 115521

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

Upvotes: 2

sumskyi
sumskyi

Reputation: 1835

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

Upvotes: 4

Related Questions