Main Content

Web and console - same principle, same code - Ruby example

Archive - Originally posted on "The Horse's Mouth" - 2013-02-14 08:23:39 - Graham Ellis

Courses for newcomers to programming start with showing the mechanism of how to enter a program, how to prepare that program to be run, and how to actually run it. We then show them how to read an input (usually from the keyboard), calculate, save values into variables and resuse them a few lines later, and output resuts. That's a tried and tested formula for getting something up and running quickly, and that "something" being a useful program. But it's a very long way indeed from a web application, which is what many delegates are writing these days ... or that's how it looks.

And so - at the end of the first day of our "Learning to program in ..." courses, we take the code that we've written and put it into context - take it a step further, and a small step to being recognisable in their environment. It's helpful in putting stuff in context, and it's motivational in that it helps delegates see where they're going.

• In First Principles terms, keyboard to screen is the same thing as browser input to browser output via a web server - both are using Standard In and Standard Out - the process's main IO channels.

• In First Principle terms, reading from a file is just like reading from the keyboard - it's a stream of data from which the next line's returned each time you do a read.

And applying those first principles, a program that goes keyboard to screen can rapidly be converted to going data file to browser window. I've put a program that I wrote at the end of the very first day of programming for delegates this week, which runs on both a web server (via CGI) and stand alone from the keyboard. Source is [here].

Being a "first day program", I've used straightforward language elements rather than shorter / more efficient ones that come later in the course, and this has lead to a degree of repetition which - in the longer term - I would frown upon as each repeat doubles up the changes and testing needed when the program needs alteration.

Being a "dual use" program, I've not put any specifics / HTML formatting into it ... such things would come in an applicaton program, leaving an API for the data handling clean for any environment.