Jun 12 2002

Introduction to the Ruby Language

Published by at 12:00 am under Presentations   

On June 12, 2002, I gave a talk at the St. Louis Unix user group introducing the Ruby language. The presentation is available for download here:

http://kylecordes.com/files/IntroToRuby.ppt

The text of the presentation, without useful formatting also appears here, so that search engines (particularly the one I need to add to this web site) will be able to find it.

We don’t use Ruby much (yet?) at Oasis Digital, but there are some interesting and useful ideas in it; I recommend looking it to expand your exposure to what’s possible in language design, even if you don’t need or plan to use yet another scripting language.

Addendum: Oasis Digital’s resident “Pythonista” pointed out that like Ruby, Python now supports multiple inheritance and garbage collection (not just reference counting).


Introduction To Ruby

Kyle Cordes

Oasis Digital Solutions Inc.

St. Louis Unix User Group

June 12, 2002

Agenda

What is Ruby?

Features

Look at some code

Resources

Discussion

What is Ruby?

“Ruby is the interpreted scripting language for
quick and easy object-oriented programming.”

What does that mean?

Interpreted

Actually it gets “compiled” to an internal representation
when loaded, somewhat like Perl

Scripting

Everyone says this, but it’s not really clear what
it means

Object Oriented

Every piece of data is an object

History of Ruby

Written by Yukihiro Matsumoto, a.k.a “Matz”

started in 1993

it’s Ruby, or ruby, but not RUBY

Matz wanted an OO scripting language; goal to be
better than Perl, more OO than Python

Ruby’s Growth

more popular than Python in Japan since 1999

Gaining popularing here

I could find no real numbers

Very few job posts

Ruby and XP

Ruby gets mentioned a lot in the Extreme Programming
community.

Likely reasons:

Ruby support very “soft” code

Ruby is highly OO

Ruby bears resemblance to Smalltalk

Features of Ruby

Explanations and

Examples

Simple Syntax

Many thing that look like syntax, are not.

Ruby documents talk about a “Principle of Least
Surprise” (POLS), which means that things work the way you expect them to,
with few special cases or exceptions;

Personally, I find there are really a lot of those
exception.

Line Oriented

Lines of code don’t end in “;”

Rather, they end at the end of the line, unless
they obviously don’t:

puts 3 + 4 +
5 + 6

I like this – because it optimizes for the usual
case (one statement per line)

Control Structures and Block Structure

if n > 3
puts “this”
elsif n >2
puts “that”
else
puts “whatever”
end

Note that the “begin” of a block is implicit.

Perl-like “if”

print “this” if someVar > 5

doSomeWork while temperature < 65

Array and Hashes are built in

… like Perl, Python, etc.

arr = []
arr << 45 # adds to the end

h = {}

h[‘key’] = ‘Value’

Regular Expressions

Built in, very Perl-like

if str =~ /Some|Thing/
print “Found it”
end

Dynamically Typed

Ruby uses late binding; decisions deferred until
run time

You can change your design without changing types
everywhere.

Note that it is type-safe

No variable declarations

You don’t declare variable types

You don’t declare variables at all

The “first use” rule tells Ruby the difference between
a variable and a method

Examples

a = “this”
a = 45
a = SomeClass.new

Big Numbers

num = 7

9.times {

print ‘num is a ‘ , num.type , ‘ and its value
is ‘ , num

num = num * num

}

Here Documents

str1 = <<END
some text
and some more
END

Nothing new here, just a nice Perlism.

Structured Exception Handling

(like Java, C++, Python, etc.:)

begin
# code here
rescue NameError => err # “catch”
# deal with it
ensure # like “finally”
# do this no matter what
end

Operators are Syntax Sugar

They are just aliases for methods.

Pure OO

All data in Ruby is an object

All code is a method.

Even the basic types (numbers) are objects, though
there are some optimizations under the hood.

Single Inheritance

Like Java, C#, Python

Not like C++

Mixin modules, which are unique toRuby, support
many of the same ideas as MI.

Access Conrol

Public

Like C++

Protected

Like C++

Private

Rather unusual – private to this instance, not
this class
. This actually makes a lot of sense.

Mix-in Modules

Modules are sets of methods that can be added in
to any class

They typically give it a “personality”

Example: Enumeration

Enumeration Mixin

Provides, with a tiny bit of help from the programmer,
all the normal “list” methods:

each

each_with_index

sort

collect

detect

reject

select

entries

find

grep

include?

map, max

more…

Blocks

array = [1, 2, 3]
x = 5
array.collect! { | elem | elem + x }
p array # => [6, 7, 8]

More Block Examples

array.each { | elem | puts elem }
hash.each { | key, val | puts “#{key} => #{val}” }
file.each { | line | puts line }

array.each_with_index { | elem, i |
puts “array[#{i}] = #{elem}”
}

How Blocks Work

There is nothing special about the build in iterarors;
you can write your own easily:

def method1(x)
5.times {
yield(x)
}
end

methods(9) { |x| puts x }

Closures

Closures are what blocks create; they “enclose”
the state of the variables in scope at the time the block was created.

Garbage Collection

Ruby is a GC language. You only allocate memory,
never explicitly free it.

This is true GC, not reference counting like Python.

Open question: how robust and performant is the
garbage collector?

Ranges

the range syntax

(1..10).each { |i| sum += I }

(0 .. 9).each { | i | sum += i }
(‘a’ .. ‘z’).each { | str | puts str }
(0 … array.size).each { | i | puts array[i] }

Ranges stay Ranges

Ranges are a class Range; they don’t expand to a
list, so you can say this without any memory problems:

range1 = 10 .. 10000000

Introspection (reflection)

Ruby code and inspect itself at runtime, determine
an object’s methods, etc.

Try this:

a = [1, 2, 3] # create an object of class Array

puts a.methods # get a list of its methods

Naming Conventions

The naming conventions are part of the language,
including first-letter case:

@instanceVar

@@classVar

$global

CONSTANT

everythingElse

Method aliasing

Many methods in Ruby have more than one name;

This is considered a convenience.

I am not convinced.

C integration

Ruby comes with a toolkit to easy make C code callable
from Ruby

Singleton methods

A singleton method is an instance method associated
with one specific object.

class Foo
end
foo = Foo.newdef foo.hello
puts “Hello”
end

Singleton classes

class << foo
attr :name, TRUE
def hello
“hello. I’m ” + @name + “\n”
end
end

This modifies one instance by adding a new method

OS-Independent Threading

Ruby contains language-level threading;

Of course this is cross-platform,

But of course it also does not natively thread,
so one OS operation blocks all the Ruby threads.

Portable

Most Unixes

Linux

Macintosh (OS 9 and OS X)

BeOS

OS/2

DOS

Windows 95/98/NT/2K

Cygwin and non-Cygwin variations

Great One-Liners

IO.foreach(“file”) {| x | print x}

sort files by date:
Dir.glob(“*”).sort{|a,b| File.mtime(b) <=> File.mtime(a)}

OLE / ActiveX support

(Windows – boo, hiss!)

ie = WIN32OLE.new(‘InternetExplorer.Application’)
ie.visible = true
ie.gohome

You can also call any function in a DLL, access
ODBC, etc.

More Examples

class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age.to_i
end
def inspect
“#@name (#@age)”
end
end

Continued

p1 = Person.new(‘elmo’, 4)
p2 = Person.new(‘zoe’, 7)p1 # -> elmo (4)
p2 # -> zoe (7)

Advantages

Powerful, flexible language

Simple, consistent syntax ?

Simple like Perl some would say 🙂

Easy to learn the basics (especially if coming from
another P____ language)

Very OO

Good systems-admin features in the libraries (manipulating
files, etc.)

… continued

Core langauge is mature (seven years old)

Rich libraries

Helpful community

The author of the language answers questions on
the main mailing list.

… and Disadvantages

Not well known; not many installations

(then again this was also true for Perl, Java, etc.)

No big vendors pushing it

Documentation is not as broad as more common languages

and many are in Japanese

…. continued

Only a few books

Weak (IMO) thread implementation

Not many Ruby developers to hire

Some parts are not so mature

One implementation, one main author, etc.

Ruby Compared to Python

http://www.rubycentral.com/faq/rubyfaqall.html

Ruby has objects all the way down, while Python
is moving in that direction

Ruby is a bit more dynamic

Ruby has blocks

Ruby Compared to Python

Python appears to be in much broader use in the
US.

Python has more apps using it

Python is simpler, Ruby has more Perlisms in the
syntax

Ruby compared to Perl

Ruby has a lot of Perlisms

Ruby is pervasively OO, while Perl supports OO in
addition to everything else.

Perl is much more mature.

Resources, Downloads, Etc.

Getting Ruby and learning more about it.

Downloading it:

Unix or Linux: http://www.ruby-lang.org/

Windows:

http://www.rubycentral.com/

http://pragmaticprogrammer.com/

Free software, distributed under GPL, or an Artistic-like,
less restrictive license.

Ruby Application Archive

The RAA aims to be the “CPAN” of the Ruby world.

Like other things that aim to be like CPAN for other
languages, it is much less mature then CPAN.

Some of the libraries are in Japanese.

http://www.ruby-lang.org/en/raa.html

The Pragmatic Programmers

Dave Thomas and Andy Hunt:

wrote a book with this title

have a company with this name

wrote a Ruby book

are leading users of Ruby, apparently for their
consulting engagements.

RubyCentral

Think of this as a “community home page” for Ruby:

http://www.rubycentral.com/

The PP book is here for download:

http://www.rubycentral.com/book/

Links

http://www.ruby-lang.org/

http://pragmaticprogrammer.com/

http://www.pragmaticprogrammer.com/talks/perlmongers/img19.htm

http://www.pragmaticprogrammer.com/talks/perlmongers/perlmongers.htm

Discussion Topics:

What is a scripting language, anyway?

Anyone here using Ruby?

How hard is it to introduce a new language to a team / project / company?

What minimum features are needed for a language to be “ready for prime time”? Life can be hard without a profiler, for example.

THE END

Slides will be on my site:

http://kylecordes.com

If you found this post useful, please link to it from your web site, mention it online, or mention it to a colleague.

No responses yet

Comments are closed.