Pass block passed to method to another method in Ruby

You can reference the block explicitly

def discard(&block)
  self - self.keep(&block)
end

or implicitly

def discard
  self - self.keep(&Proc.new {})
end

In your case, I would suggest the first approach.


In the second example, &Proc.new {} doesn't pass a block, it creates a new empty one. One should omit {} and write it as self.keep(&Proc.new) or just keep(&proc) as self. is redundant and proc is the recommended synonym for Proc.new:

# passes on the block or the absence of a block
def discard(&block)
  self - keep(&block)
end

# passes on the block and fails if no block given
def discard
  self - keep(&proc)
end

Both Proc.new and proc without a block use the block of the current method.

&proc will fail if discard doesn't get a block. So the first example is the best if you want to pass the block or the absence of a block (&nil passes no block at all). The second example (as I changed it) is the best if missing block is an error.

In both cases, each time 'discard' is called, a new 'Proc' object is created, and it's not free.

Tags:

Ruby

Block