Starting with Ruby - part 2

So, here we are. By now you have Ruby up and running, and you’re itching to flex those coding muscles (no? OK, back to the beginning for you). We’re going to kick off with a few of the basics, using irb. In going through the inevitable Hello World example, you’ve seen how to just echo stuff to the console. But what about something, well, more? For those of you coming from a Java background, this “suck it and see” approach using the Ruby shell (irb) is rather pleasant. We’re going to write simple programs, and play with them, no classes or method definitions required (yet). Without further ado then, fire up irb and type or paste this in (remember to hit the return key when you’re done):

animals = ["dog", "aadvark", "whelk", "horse", "elephant"]

You’ve now created an array of strings called animals. Easy, and not entirely unfamiliar I’ll warrant. Now for the first tip: typing all those quotes and commas is a faff. Don’t do that again, do this instead:

animals = %w[dog aadvark whelk horse elephant zebra ant duck frog]

%w is a splendid shortcut which means we can do away with quotes and commas when creating arrays of strings. In fact, I’m so excited about it I added some more animals just because. OK, now let’s do something with our beasts:


Huzzah! But hold on soldier, type animals into irb. What happens?

irb(main):001:0> animals
=> ["dog", "aadvark", "whelk", "horse", "elephant", "zebra", "ant", "duck", "frog"]

Boooooo. Back to where we were; let us try something else:

irb(main):002:0> animals.sort!
=> ["aadvark", "ant", "dog", "duck", "elephant", "frog", "horse", "whelk", "zebra"]

… and now query the animals reference again:

irb(main):003:0> animals
=> ["aadvark", "ant", "dog", "duck", "elephant", "frog", "horse", "whelk", "zebra"]

Ex-cell-ent (said in best Mr. Burns voice, fingers steepled). The imperative tone of our programming means that Ruby takes our intent to heart, and doesn’t dick about. It takes orders!

(Oh OK, adding the exclamation mark means we want Ruby to change our variable, rather than just work on a transitory copy of its contents). Anyway, try some other handy methods, see what occurs:

irb(main):004:0> animals.reverse
=> ["zebra", "whelk", "horse", "frog", "elephant", "duck", "dog", "ant", "aadvark"]
irb(main):005:0> animals.to_s
=> "[\"aadvark\", \"ant\", \"dog\", \"duck\", \"elephant\", \"frog\", \"horse\", \"whelk\", \"zebra\"]"

reverse does what you’d expect, and can be invoked on all manner of things (not numbers though!), whilst to_s is a simple “casting” method, which converts an instance to a string. There are other casts too:

to_i	#Converts to an integer
to_a	#Convert to an array

Whilst you can’t reverse an integer (although try 768.to_s.reverse), you can perform arithmetic on strings—try this: "I will eat my brussel sprouts" * 3.

On to files

So, irb is very useful but of course Ruby code is normally written in files, and can then be run from the command line (amongst other things). Time to move on therefore, to a variation on the above code snippet—this time with the array sorter as a basic Ruby program, which means our sorting “candidates” can be supplied as command line arguments. Copy this into a text file, and save it as sort.rb:

if #{ARGV.size} > 0
	puts ARGV.sort

You have now written a Ruby program which is preserved for ever more—let us run it! Open your command line and invoke it thus—we’re running our Ruby program with some additional values on the command-line:

ruby sort.rb dog aadvark whelk horse elephant zebra ant duck frog

OK, so what’s going on with this ARGV malarkey? And what’s with the hash-curly brace thingie?

ARGV is an in-built reference in Ruby, and points to values issued on the command line at run-time (if you know Java, it’s akin to String args[] in a main method). To manipulate it, you see that we surround it with a hash (“pound” for my transatlantic chums)-curly brace combo, and this is how Ruby interpolates expressions. For example, if I pass some method a variable called “name”, if I want to get to the content of that variable, I refer to it in code as #{name}. Ruby is what some refer to as an “idiomatic language”—there’s a “Ruby way” to doing things, it’s pretty expressive. As a result of this, the hash-curly brace doo-dad (technical term) means that you can add in method calls and other manipulations to your heart’s content. In our simple example, you see that we don’t just reference ARGV’s contents; at the same time we also grab its size attribute, and use that as deciding factor re proceeding with the code or not.

Get us! We’re being all idiomatic and wot-not, and we now know how to do a tiny control structure in Ruby (OK, OK, it’s an if statement…)

The final bit of this wee program has us calling the built-in sort method, this time on the ARGV reference, and writing the result out to the console via the puts method. As an aside, if you want to see the sorted arguments expressed in their actual state (or at least, a human-readable version of their actual state), swap the puts directive in your code for p, and try running the code again. Interesting eh? (More on that later…)

We’re flying now, and we have the basics down. It’s time to step up, code our own classes and methods. What say ye? Onwards to part three!

A note re running Ruby files on the command line: if you’re on a Unix-derived system, you can make Ruby files executable. Add a “shebang” to the top of your source file (#!/usr/bin/env ruby should suffice in most cases), and then do a chmod +x on the file to make it executable. This is, I grant you, quite a lot of work just to drop the “ruby” prefix :-)

Further reading


  1. For the most comprehensive video training on rails, check out Really enjoying it and includes good examples of TDD (test driven development)Jim Knight#
  2. Bad day for links Jim?

    We’re coming to Rails soon. I think a grounding in Ruby helps first.

    http://railstutorial.orgBen Poole#
  3. we need to discuss your animal classification systemCoatsie#

Comments on this post are now closed.


I’m a software architect / developer / general IT wrangler specialising in web, mobile web and middleware using things like node.js, Java, C#, PHP, HTML5 and more.

Best described as a simpleton, but kindly. You can read more here.