Search code examples
rubyarraysblockeachenumerable

Refer to anonymous array within each/block


I have the following in Ruby:

arr = [1, 2]
arr.each{|n| arr << n unless n > 2_000}

Is there any way to reference my array from within the block if I define it anonymously?

[1,2].each{|n| self << n unless n > 2_000}

Or something? I'm guessing not because I can't think of a way that I would reference it.


Solution

  • here are similar (although outdated) questions:

    Call to iterating object from iterator

    How to get a reference to a 'dynamic' object call?

    also you could create a one-liner this way:

    (arr = [1, 2]).each{|n| arr << n unless n > 2_000}