I am working with Ruby scripting language. I have a snippet here. Just want to know what is happening inside that with in the loop. Here is my code
#!/usr/bin/ruby
presidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton", "Bush2"]
for ss in 0...presidents.length
print ss, ": ", presidents[presidents.length - ss - 1], "\n";
end
I know that it is to print the array in reverse order, but my intention is to know what is happening in
"presidents[presidents.length - ss - 1]"
Please help me understanding this. I am really confused with this.
It means that, whoever wrote this code, he was still learning Ruby :-p. That’s more idiomatic and, I hope, self-explanatory:
About
presidents[presidents.length - ss - 1]:ssstarts at 0, solength-0-1 = length-1-> last element ofpresidents. On the last iteration of the loop you havelength - (length-1) -1 = 0, so the first element ofpresidentsis shown. A simple reverse, nothing fancy.