1

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.

diplosaurus
  • 2,538
  • 5
  • 25
  • 53

3 Answers3

1

Changing the array when you are iterating it may cause infinite loop.

You could do below:

arr = [1, 2]
arr += arr.select { |n| n <= 2000 }
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Bummer, that ruins my Project Euler fibonnaci solution: `arr.each{|x| arr << arr[-1] + fib[-2] unless x > 4_000_000 }.select{|n| n % 2 == 0}.reduce(:+)` – diplosaurus Mar 14 '14 at 04:29
1

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}
Community
  • 1
  • 1
trushkevich
  • 2,657
  • 1
  • 28
  • 37
0
[].tap { |e| e.concat([1,2,20000].select { |n| n <= 2000 })