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?
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.
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.
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.
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!" }
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.
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