Thursday, April 7, 2011

Reverse program done with help (Ruby Program pt. 8)

On Tuesday night I went to the Ruby L.A. group and had a good time. Learned quite a bit. And the reverse program is done! So I described what I wanted to do and Evan, the group leader, had an even more elegant solution.

So my idea was (as I described in a previous post) to go through the line and read each character match it to the Unicode character-sets boundaries (using their hex-code numbers) and ingest it into an array in one or two or three character chunks per element. Then reverse the order of the elements in the array by passing them to another array and output that.

In the group I learned that arrays have a reverse method. So it's real easy to reverse them. But the coolest thing was how Evan proposed solving it.

Scan
Evan used the scan method (one I had heard about but haven't quite mastered) but here is the cool thing, by escaping the characters as Unicode the scan method basically does in one step what I wanted to do in many. Scan will spit out an array of elements that are split by whatever argument is fed to the scan method. You can have scan capture all the digits in a string, or in this case all the Unicode characters in a string. So scan check each element in order if it's a Unicode character (which all are going to be) it gets put into the array. Then I reverse the array and join it into a string again.

I had no idea you could use a Unicode Characters as an argument using what's called a regular expression. Which sound rather common and easy to understand but are in fact rather obtuse. They're a way of writing things the way the program sees them, but they are not intuitive or well explained in the books I have so far. So more on this later.

Right now the program works on any UTF8 file with no BOM(Byte Order Marking), something relatively easy to make on Notepad++.

No comments:

Post a Comment