Ruby Compendium - Syntax

Teaching you how to program in Ruby goes beyond the scope of this book, however, this section will show you at least what Ruby code looks like. If you know another programming language already, some things may already be familiar to you. If you don't, hopefully the following code will not appear too intimidating.

 1# This is a comment and will not be executed 
 2# by the Ruby interpreter.
 3#
 4# This is not the usual 'Hello World' example, so 
 5# don't worry if you don't understand everything. 
 6# This example is meant to give you a general feeling 
 7# of what it is like to write Ruby programs.
 8
 9require 'pathname'   # Here we're requiring an external library
10                     # which is part of the Ruby Standard Library.
11
12class FilePrinter
13
14  # Constructor method
15  def initialize(path)
16    # This method expects a valid path, however Ruby is dynamically-typed
17    # so anything can be passed to this method.
18    # To check that the input value is valid, just check if if it behaves
19    # like a path. This is called 'duck typing'.
20    raise RuntimeError, "Invalid path: #{path}" unless path.respond_to? :basename
21    @path = path
22    @name = @path.basename
23  end
24
25  def show
26    # Ruby objects and expressions can be interpolated in strings
27    puts "  #@name -- #{@path.stat.size} bytes"
28  end
29
30end
31
32class DirPrinter < FilePrinter # Definition of a child class
33
34  def initialize(path)
35    super # Call to the parent's constructur
36    @children = @path.children
37  end
38
39  def show
40    puts "  #@name/ -- #{@children.length} item(s)"
41  end
42
43end
44
45# No parenthesis are required unless needed!
46pwd = Pathname.new Dir.pwd
47
48puts "Current Directory: #{pwd}"
49
50# Get the children items of the current directory, 
51# select only directories, 
52# sort them alphabetically,
53# and for each one of them...
54pwd.children.select{|i| i.directory? }.sort.each do |item|
55  # Call the show method, printing the 
56  # directory name and the number of child items
57  DirPrinter.new(item).show
58end
59
60pwd.children.select{|i| !i.directory? }.sort.each do |item|
61  FilePrinter.new(item).show
62end