Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass block to delegated << Array method in Ruby

Tags:

ruby

I have created a delegated Array class like this:

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 am overriding the << method and I want to be able to pass a block in that I can use as a predicate.

I have the following test that 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 a block to << and if so, can anyone point me in the right way?

like image 280
dagda1 Avatar asked Mar 10 '26 07:03

dagda1


1 Answers

You can do it using method call syntax:

arr.<<(part, &predicate)
like image 163
sepp2k Avatar answered Mar 11 '26 22:03

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!