Reputation: 3
I came across this iterator that reverses a string. I've tried to break it down in order to understand what it is doing, but don't seem to have come much further.
2.0.0-p643 :053 > s1 = "reverse"
=> "reverse"
2.0.0-p643 :054 > (0...(s1.length/2)).each {|i| s1[i],s1[s1.length-i-1]=s1[s1.length-i-1],s1[i]}
=> 0...3
2.0.0-p643 :055 > s1
=> "esrever"
Can someone help me break down each part of the iteration?
2.0.0-p643 :056 > (0...(s1.length/2))
=> 0...3
The first object only gives me 0..3. How is it iterating through the entire word?
And why do you need s1[i] twice in the iteration?
Upvotes: 0
Views: 45
Reputation: 37207
This isn't all that complex -- mostly just obscured by the formatting. If you write it out on multiple lines, it looks like this:
(0...(s1.length/2)).each do |i|
s1[i], s1[s1.length-i-1] = s1[s1.length-i-1], s1[i]
end
If you're not comfortable with multiple assignment, you can break it down further with a temporary variable:
(0...(s1.length/2)).each do |i|
temp = s1[i]
s1[i] = s1[s1.length-i-1]
s1[s1.length-i-1] = temp
end
It's iterating over the left half, and swapping each character with the corresponding character in the right half (the first with the last, the second with the second last, etc.).
Upvotes: 1