4

Consider the following

arr = [5, 4, 3, 2, 1]
arr.each_with_index { |val, index| dosomething...}

Based on my readings Ruby will iterate across the array in sequential order (5, 4, 3 ...). My question is whether this behavior is guaranteed by the language or its specification? Specifically would future versions of Ruby prevent the array from being iterated in parallel or in a different sequential order? Put differently is the sequential processing of array elements by an each function call CONVENTION or SPECIFICATION.

Let's look at these two topics separately.

Non-sequential order: Could future versions of Ruby, without violating the language specification, possibly decide that the optimal way to accomplish execution of the each_with_index is [2, 3, 5, 4, 1]?

Parallel processing: Consider a future (or perhaps existent but unknown to me) version of Ruby for large scale parallel processing. Without violating the language specification could this version of Ruby potentially decide to process 3, 2, and 1 at the same time and then after that 4 and 5?

Appreciate the feedback.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • 1
    I don't know much about language specs but .. `Arrays are ordered, integer-indexed collections of any object.` - http://ruby-doc.org/core-2.1.0/Array.html and this question addresses the threadsafety of Arrays: http://stackoverflow.com/questions/17765102/why-is-the-operation-on-an-array-in-ruby-not-atomic – Mike Campbell Feb 21 '14 at 16:59
  • The referenced question partially answers my question, in particular the portion about sequential processing. I would still like a more definitive answer about the language specification. In particular optimizations that might consider parallel processing solutions. – Courtland Caldwell Feb 21 '14 at 17:23
  • 1
    We can't really comment on an unknown/unannounced/possible implementation. An array is the basis for a queue or stack. That sort of processing has to be sequential otherwise bad things would happen. It's up to you, the developer, to specify whether multiple things can access that container, and how they'll do it. It's up to the interpreter to do what you said. Study the Thread class and you'll encounter the Queue class, which manages sequential accesses to a list of values. Parallel processing would have to honor that. – the Tin Man Feb 21 '14 at 17:27
  • 1
    It definitely will not happen; trust me ;-) – mdesantis Feb 21 '14 at 18:47

0 Answers0