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?
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 ...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With