Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4622

Pass block passed to method to another method in Ruby

$
0
0

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  endendclass Array  include Strainend

This works. But I want to do something like:

def discard  self - self.keep &blockend

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?


Viewing all articles
Browse latest Browse all 4622


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>