Skip block for delegated << Array method in Ruby

I created a delegated Array class as follows:

class LeadPartArray < DelegateClass(Array)

  def <<(part, &block)
    super(part) unless @arr.select{|p| p.text == part.text}.size > 0
  end

  def initialize(arr = [])
    @arr = arr
    super(@arr) 
  end

end

I redefine the <method, and I want to be able to pass a block that I can use as a predicate.

I have the following test, which is not even legal Ruby syntax:

  def test_should_pass_predicates_to_add
    arr = LeadPartArray.new([])
    part = LeadCapturer::LeadPart.new("text", LeadCapturer::TextTag.new, 2)
    predicate = Proc.new{|part| part.text.size < 4}
    arr <<(part, &predicate)
    assert_equal(0, arr.size)
  end

Is it possible to pass the block to <, and if so, can someone tell me the correct path?

+3
source share
1 answer

You can do this using the method invocation syntax:

arr.<<(part, &predicate)
+1
source

Source: https://habr.com/ru/post/1761808/


All Articles