Ruby - a training example that puts many language elements together to demonstrate the whole
Towards the end of our programming language training courses, we pull together all the various strands into a worked example that shows how they go together. I've just posted such an example from last week's
Ruby Programming Course ...
[here].
Let's have a look at some of the things in the example code ...
1. We've set up objects with quite a number of properties, using an array of elements passed in to the constructor. The data values themselves are then stored in a hash within the object. It saves a lot of repeating code, and it allows us to provide generic "
get" and "
set" methods. Here's the constructor:
def initialize(parts)
fn = %w(four tlc postcode grid lat long name 2005 2006 2007 2008 2009 2010)
@info = Hash.new
for num in 0...fn.length
@info[fn[num]] = parts[num]
end
end
2. The incoming data for our application comes from a tab delimited file - and the string that we read from the file is not the sort of raw data we want to pass into the constructor. That's because other applications using the same class will have the data supplied in other formats. So we have used a
factory method in the class to covert the string into an object:
def Station.factory(raw)
parts = raw.chomp.split("\t")
if parts[7].to_i > 0 && parts[12].to_i > 0
result = Station.new(parts)
else
result = nil
end
return result
end
You'll note that our factory is a static method, and that it does more that just return an object of the desired type; it can also return a false value (nil) if the data passed in doesn't describe an object, and indeed it could be extended to create all sorts of different object types based in the incoming data. The call to the factory is as follows:
if gotten = Station.factory(lyne)
which takes a line of text (in "lyne") and sets up an object which it saves into "gotten" ... which is immediately checked; the handling code for the object is in the following conditional block.
3. What happens when you compare two objects? It's going to fairly obvious for numbers, but when you com eto more complex objects - railway stations in our case - it's not so obvious. In Ruby we could redefine what the operators <, <=, ==, !=, > and >= do (as they're just methods called up with a different syntax), but in practice we'll do better to call in the
comparable mixin, and which defines each of those six in terms of a seventh - <=> - and then we can redefine just that one method.
Here's how we load the six-to-one mapping:
include Comparable
and then here's how we use the mapping:
def <=> (second)
diff = @info["2010"].to_i - second.get("2010").to_i
return diff
end
Which will return negative (less than), 0 (equal) and positive (greater than)
4. What do you get when you print out an object? The default's going to be a string that includes the object type and the address in memory it's held at. Maybe that's fine for debugging purposes, but it's a frightener to the enduser of your program. So you can redefine what's produced by printing an object by overloading the to_s method. (If you want to dump out everything in the object, take a look at the
inspect method).
def to_s
return @info["name"] + "[" + @info["tlc"] + "]"
end
In our example, we've also overwritten the "+" method so that we can add two stations together. The algorithm is just a demonstration in this case - there would need to be more complex logic to combine each attribute in a suitable way, but the purpose of the course was to teach programming rather that the detail of rail management!
5. If something in your application fails, you can catch the error by including the code that may not work into a begin / end block, with a rescue block telling the program what to do in the event of problems:
  begin
    fho = File.new("railstats.xyz","r")
  rescue StandardError
    STDERR.puts "oops!"
  else
    # [[ code to run if the file open worked ]]
  end
You'll note that I've written the error message to STDERR - that's so that any output redirection will not be applied to this particular message and it will usually appear on the user's screen rather than ending up in the output file.
(written 2011-04-23)
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
R111 - Ruby - Exceptions. [1875] What are exceptions - Python based answer - (2008-11-08)
[2615] String to number conversion with error trapping in Ruby - (2010-02-01)
[2620] Direct access to object variable (attributes) in Ruby - (2010-02-02)
[2621] Ruby collections and strings - some new examples - (2010-02-03)
[2622] Handling unusual and error conditions - exceptions - (2010-02-03)
[3177] Insurance against any errors - Volcanoes and Python - (2011-02-19)
[3433] Exceptions - a fail-safe way of trapping things that may go wrong - (2011-09-11)
[3435] Sorta sorting a hash, and what if an exception is NOT thrown - Ruby - (2011-09-12)
[4008] Reading and checking user inputs - first lessons - Ruby - (2013-02-17)
[4675] Exceptions in Ruby - throwing, catching and using - (2016-05-17)
R108 - Ruby - More Classes and Objects [184] MTBF of coffee machines - (2005-01-20)
[656] Think about your design even if you don't use full UML - (2006-03-24)
[1217] What are factory and singleton classes? - (2007-06-04)
[1587] Some Ruby programming examples from our course - (2008-03-21)
[2292] Object Orientation in Ruby - intermediate examples - (2009-07-16)
[2601] Ruby - is_a? v instance_of? - what is the difference? - (2010-01-27)
[2603] Ruby objects - a primer - (2010-01-29)
[2604] Tips for writing a test program (Ruby / Python / Java) - (2010-01-29)
[2616] Defining a static method - Java, Python and Ruby - (2010-02-01)
[2623] Object Oriented Ruby - new examples - (2010-02-03)
[2717] The Multiple Inheritance Conundrum, interfaces and mixins - (2010-04-11)
[2977] What is a factory method and why use one? - Example in Ruby - (2010-09-30)
[2980] Ruby - examples of regular expressions, inheritance and polymorphism - (2010-10-02)
[3142] Private and Public - and things between - (2011-01-22)
[3154] Changing a class later on - Ruby - (2011-02-02)
[3158] Ruby training - some fresh examples for string handling applications - (2011-02-05)
[3760] Why you should use objects even for short data manipulation programs in Ruby - (2012-06-10)
[3781] Private, Protected, Public in Ruby. What about interfaces and abstract classes in Ruby? - (2012-06-23)
[3782] Standard methods available on all objects in Ruby - (2012-06-23)
[4366] Changing what operators do on objects - a comparison across different programming languages - (2014-12-26)
[4504] Where does Ruby load modules from, and how to load from current directory - (2015-06-03)
[4550] Build up classes into applications sharing data types in Ruby - (2015-10-23)
[4551] Testing your new class - first steps with cucumber - (2015-10-23)
Q907 - Object Orientation and General technical topics - Object Orientation: Design Techniques [80] OO - real benefits - (2004-10-09)
[236] Tapping in on resources - (2005-03-05)
[507] Introduction to Object Oriented Programming - (2005-11-27)
[534] Design - one name, one action - (2005-12-19)
[747] The Fag Packet Design Methodology - (2006-06-06)
[831] Comparison of Object Oriented Philosophy - Python, Java, C++, Perl - (2006-08-13)
[836] Build on what you already have with OO - (2006-08-17)
[1047] Maintainable code - some positive advice - (2007-01-21)
[1224] Object Relation Mapping (ORM) - (2007-06-09)
[1435] Object Oriented Programming in Perl - Course - (2007-11-18)
[1528] Object Oriented Tcl - (2008-02-02)
[1538] Teaching Object Oriented Java with Students and Ice Cream - (2008-02-12)
[2169] When should I use OO techniques? - (2009-05-11)
[2170] Designing a heirarcy of classes - getting inheritance right - (2009-05-11)
[2327] Planning! - (2009-08-08)
[2380] Object Oriented programming - a practical design example - (2009-08-27)
[2501] Simples - (2009-11-12)
[2523] Plan your application before you start - (2009-12-02)
[2741] What is a factory? - (2010-04-26)
[2747] Containment, Associative Objects, Inheritance, packages and modules - (2010-04-30)
[2785] The Light bulb moment when people see how Object Orientation works in real use - (2010-05-28)
[2865] Relationships between Java classes - inheritance, packaging and others - (2010-07-10)
[2878] Program for reliability and efficiency - do not duplicate, but rather share and re-use - (2010-07-19)
[2889] Should Python classes each be in their own file? - (2010-07-27)
[2953] Turning an exercise into the real thing with extreme programming - (2010-09-11)
[3063] Comments in and on Perl - a case for extreme OO programming - (2010-11-21)
[3085] Object Oriented Programming for Structured Programmers - conversion training - (2010-12-14)
[3454] Your PHP website - how to factor and refactor to reduce growing pains - (2011-09-24)
[3607] Designing your application - using UML techniques - (2012-02-11)
[3763] Spike solutions and refactoring - a Python example - (2012-06-13)
[3798] When you should use Object Orientation even in a short program - Python example - (2012-07-06)
[3844] Rooms ready for guests - each time, every time, thanks to good system design - (2012-08-20)
[3878] From Structured to Object Oriented Programming. - (2012-10-02)
[3887] Inheritance, Composition and Associated objects - when to use which - Python example - (2012-10-10)
[3928] Storing your intermediate data - what format should you you choose? - (2012-11-20)
[3978] Teaching OO - how to avoid lots of window switching early on - (2013-01-17)
[4098] Using object orientation for non-physical objects - (2013-05-22)
[4374] Test driven development, and class design, from first principles (using C++) - (2014-12-30)
[4430] The spirit of Java - delegating to classes - (2015-02-18)
[4449] Spike solution, refactoring into encapsulated object methods - good design practise - (2015-03-05)
[4628] Associative objects - one object within another. - (2016-01-20)
Some other Articles
Alternative Vote (AV) - explaining and an exampleCome as a customer, leave as a friend - Well House Manor, Hotel, WiltshireSome SVG Elements, pixel and percent positioningScalable Vector Graphics - easy, low bandwidth, high resolution, dynamic.Ruby - a training example that puts many language elements together to demonstrate the wholeOur library in MelkshamMorning in MelkshamAll possible combinations from a list (Python) or array (Ruby)Displaying a directory or file system tree - LinuxProcess every member of an array, and sort an array - Ruby