Content area
Last week Network World promised a quick tour of the Ruby language. First, they define a method. Next, the %w, that is a shortcut for creating arrays that lets you leave the quotes and commas out. The "each" method applied to the array extracts each element from the array, and the code in braces is a block that is associated with the "each" method and gets executed once for each element. If this all sounds a little convoluted they suggest you buy a copy of Programming Ruby, The Pragmatic Programmer's Guide, Second Edition, by Dave Thomas.
Full text
GEARHEAD INSIDE THE NETWORK MACHINE
That's enough festive nonsense for one season. Last week we promised a quick tour of the Ruby language so here goes: First, reread last week's Gearhead for the background (www.nwfusion.com, DocFinder: 5228). It's OK, we'll wait for you.... Right, now you're back, here's a Ruby script:
We're sure you can figure out what the output of this program would be but let us point out some interesting features: First, we define a method, add_jingle (remember, Ruby is a completely object-oriented language).
Next, the %w, that's a shortcut for creating arrays that lets you leave the quotes and commas out. The each method (called an "iterator") applied to the array extracts each element from the array and the code in braces is a "block" that is associated with the each method and gets executed once for each element.
Parameters are passed to blocks through variables identified by being bracketed by the bar symbol and that follow immediately after the braces. We could have written the program more concisely:
This is more subtle than it looks, as it involves a sort of recursive call to the method using the block as an argument.
If this all sounds a little convoluted we suggest you buy a copy of Programming Ruby, The Pragmatic Programmer's Guide, Second Edition, by Dave Thomas (published by The Pragmatic Bookshelf).
This is an excellent book. It introduces all the features of Ruby in an orderly, organized way and provides an exhaustive reference to the language. One of the great attributes of this text is readability - it really simplifies coming to grips with this rich, complex language.
You want to get an idea of what Ruby can do with TCP and threading? Check this out:
As you can see, we started a new thread for each fetch. And each acted, as it should, independently, outputting its result as each thread retrieved the targeted contents. We can't explain why there was no line feed before the second "Fetching" on the first output line - let us know if you have any ideas. We tried adding line feeds but no joy
We still are learning Ruby and it is amazing what you can do in this language with a little effort. If you use or plan to use Ruby let us know your experiences.
Happy holidays! This has been a great year for feedback and ideas from y 'all Thank you for reading and responding. New Year's resolutions to gearhead@ gibbs.com.
Copyright Network World Inc. Dec 20, 2004
