Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass block passed to method to another method in Ruby

Tags:

ruby

block

I'm trying to write a clone of the ruby keep_if and delete_if array methods. Here is my code.

module Strain   def keep     self.inject([]) do |extracts, element|       yield(element) ? extracts << element : extracts      end   end    def discard     self.inject([]) do |extracts, element|       !yield(element) ? extracts << element : extracts     end   end end  class Array   include Strain end 

This works. But I want to do something like:

def discard   self - self.keep &block end 

Desired behaviour:

[1, 2, 3].discard { |number| number < 2 } # => [2, 3] 

So I need to pass the block that is passed to the discard method, to be passed on to the keep method. How do I achieve this?

like image 738
Kappie001 Avatar asked Dec 17 '13 21:12

Kappie001


People also ask

How do you pass block to method in Ruby?

In Ruby, methods can take blocks implicitly and explicitly. Implicit block passing works by calling the yield keyword in a method. The yield keyword is special. It finds and calls a passed block, so you don't have to add the block to the list of arguments the method accepts.

What is &Block in Ruby?

The &block is a way of sending a piece of Ruby code in to a method and then evaluating that code in the scope of that method. In your example code above it means a partial named cart will be rendered in a div.

What are procs in Ruby?

A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.

What is proc and lambda in Ruby?

In Ruby, a lambda is an object similar to a proc. Unlike a proc, a lambda requires a specific number of arguments passed to it, and it return s to its calling method rather than returning immediately. def proc_demo_method. proc_demo = Proc. new { return "Only I print!" }


1 Answers

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.

like image 165
Simone Carletti Avatar answered Sep 23 '22 11:09

Simone Carletti