Strange ruby ​​for loop behavior (why it works)

def reverse(ary)
  result = []
  for result[0,0] in ary
  end
  result
end

assert_equal ["baz", "bar", "foo"], reverse(["foo", "bar", "baz"])

This works, and I want to understand why. Any explanation?

+5
source share
2 answers

If I had to rewrite this with eachinstead for/in, it would look like this:

def reverse(ary)
  result = []

  # for result[0,0] in ary
  ary.each do |item|
    result[0, 0] = item
  end

  result
end

for a in bbasically says, take each element in the array band assign it to the expression a. So, some kind of magic happens when its not a simple variable.

The syntax array[index, length] = somethingallows you to replace multiple elements, even 0 elements. Therefore, it ary[0,0] = itemsays insert itemwith a zero index, replacing the null elements. This is basically an operation unshift.


each . for , , , , . each .

+10

ary . , , : a = ["baz", "bar", "foo"]

, a[0,0] = 5 a [5, "baz", "bar", "foo"]

, , , .

+4

All Articles