Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange ruby for loop behavior (why does this work)

Tags:

for-loop

ruby

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 explanations?

like image 635
BaroldGene Avatar asked Jan 30 '13 23:01

BaroldGene


People also ask

How do you use a for loop in Ruby?

The simplest way to create a loop in Ruby is using the loop method. loop takes a block, which is denoted by { ... } or do ... end . A loop will execute any code within the block (again, that's just between the {} or do ...

How do you stop an infinite loop in Ruby?

This means that the loop will run forever ( infinite loop ). To stop this, we can use break and we have used it. if a == "n" -> break : If a user enters n ( n for no ), then the loop will stop there. Any other statement of the loop will not be further executed.

How do you use time in Ruby?

The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead. Parameter: The function takes the integer till which the numbers are returned.


1 Answers

If I were to rewrite this using each instead of 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 b basically says, take each item in the array b and assign it to expression a. So some magic happens when its not a simple variable.

The array[index, length] = something syntax allows replacement of multiple items, even 0 items. So ary[0,0] = item says to insert item at index zero, replacing zero items. It's basically an unshift operation.


But really, just use the each method with a block instead. A for loop with no body that changes state has to be one of the most obtuse and hard to read thing that doesn't do what you expect at first glance. each provides far fewer crazy surprises.

like image 159
Alex Wayne Avatar answered Oct 15 '22 03:10

Alex Wayne