P
P
Pirozhok_s_pavidlom2018-10-30 17:27:23
ruby
Pirozhok_s_pavidlom, 2018-10-30 17:27:23

How to explain the result of executing the code (element by element)?

There is an initial array: There is a code:
a = [1, 1, 1, 1, 1, 2, 2, 2, 5, 5, 6]

a.each do |item|
  a[item] += 1
end

Execution result: I seem to understand what the code above does, but I can’t explain the origin of the elements except for the very first zero a[0]
a = [1, 4, 6, 1, 1, 4, 3, 2, 5, 5, 6]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2018-10-30
@Pirozhok_s_pavidlom

a = [1, 1, 1, 1, 1, 2, 2, 2, 5, 5, 6]
There are 11 iterations in total.
#1

a[1] += 1
#a = [1, 2, 1, 1, 1, 2, 2, 2, 5, 5, 6]

#2
a[2] += 1
#a = [1, 2, 2, 1, 1, 2, 2, 2, 5, 5, 6]

No. 3
a[2] += 1
#a = [1, 2, 3, 1, 1, 2, 2, 2, 5, 5, 6]

#4
a[1] += 1
#a = [1, 3, 3, 1, 1, 2, 2, 2, 5, 5, 6]

#5
a[1] += 1
#a = [1, 4, 3, 1, 1, 2, 2, 2, 5, 5, 6]

#6
a[2] += 1
#a = [1, 4, 4, 1, 1, 2, 2, 2, 5, 5, 6]

etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question