0% found this document useful (0 votes)
49 views

Databases For A Purpose 03/03 (Programming Language) ICT Starters 8984/4293

Ruby is an object-oriented programming language created by Yukihiro Matsumoto in the mid-1990s. It is interpreted, dynamically typed, and uses garbage collection. The document discusses Ruby's features and provides examples of using Ruby in interactive sessions to perform calculations, define methods, create classes and objects, and access variables. It demonstrates evolving a simple greeting method into a class that can greet individuals or groups of people.

Uploaded by

Yann Vautrin
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Databases For A Purpose 03/03 (Programming Language) ICT Starters 8984/4293

Ruby is an object-oriented programming language created by Yukihiro Matsumoto in the mid-1990s. It is interpreted, dynamically typed, and uses garbage collection. The document discusses Ruby's features and provides examples of using Ruby in interactive sessions to perform calculations, define methods, create classes and objects, and access variables. It demonstrates evolving a simple greeting method into a class that can greet individuals or groups of people.

Uploaded by

Yann Vautrin
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Ruby

Databases for a purpose 03/03 (Programming language)


ICT Starters 8984/4293
What is Ruby?
• Ruby is a simple and powerful object-oriented
programming language, created by Yukihiro Matsumoto
(who goes by the handle “Matz” in this document and on
the mailing lists).
• Like Perl, Ruby is good at text processing. Like Smalltalk,
everything in Ruby is an object, and Ruby has blocks,
iterators, meta-classes and other good stuff.
• You can use Ruby to write servers, experiment with
prototypes, and for everyday programming tasks. As a
fully-integrated object-oriented language, Ruby scales well.
Ruby (programming language)
• Ruby is an interpreted, high-level, general-purpose
programming language. It was designed and developed in
the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

• Ruby is dynamically typed and uses garbage collection. It


supports multiple programming paradigms, including
procedural, object-oriented, and functional programming.
According to the creator, Ruby was influenced by Perl,
Smalltalk, Eiffel, Ada, BASIC, and Lisp.
Ruby features:
• Simple syntax,
• Basic OO features (classes, methods, objects, and so on),
• Special OO features (mixins, singleton methods, renaming, and so
on),
• Operator overloading,
• Exception handling,
• Iterators and closures,
• Garbage collection,
• Dynamic loading (depending on the architecture),
• High transportability (runs on various Unices, Windows, DOS, macOS,
OS/2, Amiga, and so on).
Interactive Ruby
Ruby comes with a program that will show the results of any Ruby
statements you feed it. Playing with Ruby code in interactive sessions like
this is a terrific way to learn the language.


If you’re using Windows, open Interactive Ruby from the Ruby section of
your Start Menu.
Interactive Ruby
Ruby comes with a program that will show the results of any Ruby
statements you feed it. Playing with Ruby code in interactive sessions like
this is a terrific way to learn the language.

• If you’re using Windows, open Interactive Ruby from the Ruby section of
your Start Menu.
Interactive Ruby

Ok, so it’s open. Now what?

Type this: "Hello World"


Ruby Obeyed You!
What just happened? Did we just write the world’s shortest “Hello World”
program? Not exactly. The second line is just IRB’s way of telling us the result
of the last expression it evaluated. If we want to print out “Hello World” we
need a bit more:

puts is the basic command to print something out in Ruby. But then what’s
the => nil bit? That’s the result of the expression. puts always returns nil,
which is Ruby’s absolutely-positively-nothing value.
Your Free Calculator is Here
Already, we have enough to use IRB as a basic calculator:

Three plus two. Easy enough. What about three times two? You could type it
in, it’s short enough, but you may also be able to go up and change what you
just entered. Try hitting the up-arrow on your keyboard and see if it brings up
the line with 3+2 on it. If it does, you can use the left arrow key to move just
after the + sign and then use backspace to change it to a * sign.
Your Free Calculator is Here
Next, let’s try three squared:

In Ruby ** is the way you say “to the power of”. But what if you want to go
the other way and find the square root of something?

Ok, wait, what was that last one? If you guessed, “it was figuring out the
square root of nine,” you’re right. But let’s take a closer look at things. First
of all, what’s Math?
Modules Group Code by Topic
• Math is a built-in module for mathematics. Modules serve two roles in
Ruby. This shows one role: grouping similar methods together under a
familiar name. Math also contains methods like sin() and tan().

• Next is a dot. What does the dot do? The dot is how you identify the
receiver of a message. What’s the message? In this case it’s sqrt(9), which
means call the method sqrt, shorthand for “square root” with the
parameter of 9.

• The result of this method call is the value 3.0. You might notice it’s not just
3. That’s because most of the time the square root of a number won’t be
an integer, so the method always returns a floating-point number.

• What if we want to remember the result of some of this math? Assign the
result to a variable.
Your Free Calculator is Here

As great as this is for a calculator, we’re getting away from the traditional
Hello World message that beginning tutorials are supposed to focus on…
Ruby
What if we want to say “Hello” a lot without getting our fingers all tired? We
need to define a method!

The code def hi starts the definition of the method. It tells Ruby that we’re
defining a method, that its name is hi. The next line is the body of the
method, the same line we saw earlier: puts "Hello World". Finally, the last line
end tells Ruby we’re done defining the method. Ruby’s response => :hi tells
us that it knows we’re done defining the method. This response could be =>
nil for Ruby 2.0 and earlier versions. But, it’s not important here, so let’s go
on.
The Brief, Repetitive Lives of a
Method
Now let’s try running that method a few times:

Well, that was easy. Calling a method in Ruby is as easy as just mentioning its
name to Ruby. If the method doesn’t take parameters that’s all you need.
You can add empty parentheses if you’d like, but they’re not needed.
The Brief, Repetitive Lives of a
Method
What if we want to say hello to one person, and not the whole world? Just
redefine hi to take a name as a parameter.

So it works… but let’s take a second to see what’s going on here.


The Brief, Repetitive Lives of a
Method
What if we want to say hello to one person, and not the whole world? Just
redefine hi to take a name as a parameter.

So it works… but let’s take a second to see what’s going on here.


Holding Spots in a String
What’s the #{name} bit? That’s Ruby’s way of inserting something into a
string. The bit between the braces is turned into a string (if it isn’t one
already) and then substituted into the outer string at that point. You can also
use this to make sure that someone’s name is properly capitalized:

A couple of other tricks to spot here. One is that we’re calling the method
without parentheses again. If it’s obvious what you’re doing, the
parentheses are optional. The other trick is the default parameter World.
What this is saying is “If the name isn’t supplied, use the default name of
"World"”.
Evolving Into a Greeter
What if we want a real greeter around, one that remembers your name and
welcomes you and treats you always with respect. You might want to use an
object for that. Let’s create a “Greeter” class.

The new keyword here is class. This defines a new class called Greeter and a
bunch of methods for that class. Also notice @name. This is an instance
variable, and is available to all the methods of the class. As you can see it’s
used by say_hi and say_bye.

So how do we get this Greeter class set in motion?


Create an object
Now let’s create a greeter object and use it:

Once the greeter object is created, it remembers that the name is Pat. Hmm,
what if we want to get at the name directly?

Nope, can’t do it.


Under the Object’s Skin
Instance variables are hidden away inside the object. They’re not terribly
hidden, you see them whenever you inspect the object, and there are other
ways of accessing them, but Ruby uses the good object-oriented approach of
keeping data sort-of hidden away.

So what methods do exist for Greeter objects?


Under the Object’s Skin
Whoa. That’s a lot of methods. We only defined two methods. What’s going
on here? Well this is all of the methods for Greeter objects, a complete list,
including ones defined by ancestor classes. If we want to just list methods
defined for Greeter we can tell it to not include ancestors by passing it the
parameter false, meaning we don’t want methods defined by ancestors.

Whoa. That’s a lot of methods. We only defined two methods. What’s going
on here? Well this is all of the methods for Greeter objects, a complete list,
including ones defined by ancestor classes. If we want to just list methods
defined for Greeter we can tell it to not include ancestors by passing it the
parameter false, meaning we don’t want methods defined by ancestors.

So, it knows say_hi, and to_s (meaning convert something to a string, a


method that’s defined by default for every object), but it doesn’t know
name.
Altering Classes—It’s Never Too Late
But what if you want to be able to view or change the name? Ruby provides
an easy way of providing access to an object’s variables.

In Ruby, you can reopen a class and modify it. The changes will be present in
any new objects you create and even available in existing objects of that
class. So, let’s create a new object and play with its @name property.

Using attr_accessor defined two new


methods for us, name to get the value,
and name= to set it.
Greeting Anything and Everything,
MegaGreeter Neglects None!
This greeter isn’t all that interesting though, it can only deal with one person
at a time. What if we had some kind of MegaGreeter that could either greet
the world, one person, or a whole list of people?

• Let’s write this one in a file instead of directly in the interactive Ruby
interpreter IRB.

• To quit IRB, type “quit”, “exit” or just hit Control-D.


Greeting Anything and Everything,
MegaGreeter Neglects None!
Greeting Anything and Everything,
MegaGreeter Neglects None!
Greeting Anything and Everything,
MegaGreeter Neglects None!
Greeting Anything and Everything,
MegaGreeter Neglects None!
Save this file as “ri20min.rb”, and run it as “ruby ri20min.rb”. The
output should be:

There are a lot of new things thrown into this final example that
we can take a deeper look at.
Ruby
So, looking deeper at our new program, notice the initial lines,
which begin with a hash mark (#). In Ruby, anything on a line
after a hash mark is a comment and is ignored by the interpreter.
The first line of the file is a special case, and under a Unix-like
operating system tells the shell how to run the file. The rest of
the comments are there just for clarity.
• Our say_hi method has become a bit trickier:

It now looks at the @names instance variable to make decisions.


If it’s nil, it just prints out three dots. No point greeting nobody,
right?
Cycling and Looping—a.k.a. Iteration
If the @names object responds to each, it is something that you
can iterate over, so iterate over it and greet each person in turn.
Finally, if @names is anything else, just let it get turned into a
string automatically and do the default greeting.

Let’s look at that iterator in more depth:

each is a method that accepts a block of code then runs that


block of code for every element in a list, and the bit between do
and end is just such a block. A block is like an anonymous function
or lambda. The variable between pipe characters is the parameter
for this block.

What happens here is that for every entry in a list, name is bound
to that list element, and then the expression puts "Hello
#{name}!" is run with that name.
Cycling and Looping—a.k.a. Iteration
Most other programming languages handle going over a list
using the for loop, which in C looks something like:

This works, but isn’t very elegant. You need a throw-away


variable like i, have to figure out how long the list is, and have to
explain how to walk over the list. The Ruby way is much more
elegant, all the housekeeping details are hidden within the each
method, all you need to do is to tell it what to do with each
element. Internally, the each method will essentially call yield
"Albert", then yield "Brenda" and then yield "Charles", and so on.
Blocks, the Highly Sparkling Glint on
the Edge of Ruby
The real power of blocks is when dealing with things that are
more complicated than lists. Beyond handling simple
housekeeping details within the method, you can also handle
setup, teardown, and errors—all hidden away from the cares of
the user.
Blocks, the Highly Sparkling Glint on
the Edge of Ruby
The say_bye method doesn’t use each, instead it checks to see if
@names responds to the join method, and if so, uses it.
Otherwise, it just prints out the variable as a string.

This method of not caring about the actual type of a variable, just
relying on what methods it supports is known as “Duck Typing”,
as in “if it walks like a duck and quacks like a duck…”.

The benefit of this is that it doesn’t unnecessarily restrict the


types of variables that are supported. If someone comes up with
a new kind of list class, as long as it implements the join method
with the same semantics as other lists, everything will work as
planned.
Kicking Off the Script
So, that’s the MegaGreeter class, the rest of the file just calls
methods on that class. There’s one final trick to notice, and that’s
the line:

__FILE__ is the magic variable that contains the name of the


current file. $0 is the name of the file used to start the program.
This check says “If this is the main file being used…” This allows a
file to be used as a library, and not to execute code in that
context, but if the file is being used as an executable, then
execute that code.
Consider Yourself Introduced
So that’s it for the quick tour of Ruby. There’s a lot more to
explore, the different control structures that Ruby offers; the use
of blocks and yield; modules as mixins; and more. I hope this
taste of Ruby has left you wanting to learn more.

You might also like