Search code examples
rubyblockself

Is it possible for an undeclared enumerable object to be able to call itself within a block?


I recently asked a question today (Equality test on three or more objects) where I was trying to determine an elegant way to run an equality test on a set of 3 or more objects. One of the solutions turned out to be something like this:

array = [1,1,1,1]
array.all? {|x| x == array.first }

I'm wondering if it would be possible to reduce this to just one line, so that I could do something that would be interpreted like this:

[1,1,1,1].all? {|x| x == [1,1,1,1].first }
#=> true

where somehow I'm able to reference the initial object being called on by the block without first having to declare that object in a previous line. In pseudo-code what I'm trying to do is something like this:

[1,1,1,1].all? {|x| x == object_being_called_on_by_block.first }
#=> true

I've also tried this, but did not work:

[1,1,1,1].all? { |x| x == self.first }

Solution

  • This has been frequently asked on SO, and is frequently requested as a feature on Ruby core. So far, a Ruby core developer recommends this:

    [1,1,1,1].tap{|a| break a.all?{|x| x == a.first}}
    

    If you don't mind about performance, you can do:

    [1,1,1,1].instance_eval{all?{|x| x == first}}