Ruby is a programming and scripting language, with an elegant syntax, which is designed to be simple and pleasant to use.
Let's start this tutorial with a small script, that defines a function, with one parameter, which prints a message in the console:
def hello(msg) puts "Hello, #{msg}" end # call of the function hello("how are you?")
Running this script in the console:
$ ruby hello.rb Hello, how are you?
Now let's see how to create, and instantiate an object:
class SVG def initialize(width, height) @width = width @height = height @buffer = <<~SVG <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"#{@width}\" height=\"#{@height}\">\n SVG end def add_circle(cx, cy, r, fill) str = "<circle cx=\"#{cx}\" cy=\"#{cy}\" r=\"#{r}\" fill=\"#{fill}\" />\n" @buffer << str end def print puts @buffer puts "</svg>" end end # Instantiation of the object, and call some methods doc = SVG.new(180, 140) doc.add_circle(60, 50, 22, "limegreen") doc.add_circle(78, 60, 10, "darkred") doc.print
An object is like a structure encapsulating private variables, and functions
performing operations on, or with, the structure.
The functions encapsulated inside an object are called "methods".
The method initialize()
is the initialiser.
This is the method that is called to initialise the object, when a new object of this class
is instantiated with .new()
.
SVG is a document format for graphics, with vectorial shapes (shapes defined with lines, and curves).
Calling the script above:
$ ruby r.rb
Will produce the following SVG document:
<svg xmlns="http://www.w3.org/2000/svg" width="180" height="140"> <circle cx="60" cy="50" r="22" fill="limegreen" /> <circle cx="78" cy="60" r="10" fill="darkred" /> </svg>
The output of this script can then be redirected to a file:
$ ruby r.rb > r.svg $ inkview r.svg
If you visualise it with an image viewer, you will see this vectorial image: